【问题标题】:Parsing a list that contains Str and Ints解析包含 Str 和 Ints 的列表
【发布时间】:2015-01-10 22:54:09
【问题描述】:

我要做的是获取一个像“['Smith', '13', '19', '8', '12']” 这样的列表,我试图从中取出 int将它们全部加起来以计算平均值。有人知道怎么做吗?

【问题讨论】:

  • 您自己尝试过吗? SO 不是免费的编码服务;你不能只是在这里复制/粘贴你的作业。请向我们展示您迄今为止所做的尝试,我们将非常乐意帮助您解决遇到的任何具体问题。
  • 如果你是负责这个数据结构的人:改变它!
  • @Mike 您可以接受对您有最大帮助的答案。

标签: python string list int


【解决方案1】:

你可以这样做:

# go through each member of your list and call the 
# builtin string method `isdigit` check out the documentation
digits = [int(s) for s in your_list if s.isdigit()]
# use the built in `sum` function and the builtin `len` function
sum(digits) / len(digits)

【讨论】:

  • 这帮了我很大的忙,我的一些问题被零除,但这让我明白我做错了什么谢谢
【解决方案2】:

使用try

sum = 0
number_of_ints = 0
for items in ['Smith', '13', '19', '8', '12']:
    try:
        sum += int(items)
        number_of_ints+=1
    except:
        pass
print sum/number_of_ints

基本上,这会尝试将其添加到sum。如果失败,则继续。

【讨论】:

    【解决方案3】:

    试试这个:

    myList = ['Smith', '13', '19', '8', '12']
    count = 0
    total = 0
    
    for i in myList:
        if i.isdigit():
            count += 1
            total += int(i)
    
    average = total / count
    

    【讨论】:

      猜你喜欢
      • 2012-12-11
      • 2020-05-25
      • 2021-06-15
      • 1970-01-01
      • 2020-07-29
      • 2019-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多