【问题标题】:Selection in dictionary with str and int - Python使用 str 和 int 在字典中选择 - Python
【发布时间】:2017-10-16 04:26:45
【问题描述】:

我一直在尝试做的是对“字典”的值求和。我得到的错误是 'str' object is not callable。

根据我对 Stack Overflow 的研究,这是因为字典的某些值是字符串。但我认为我在循环中引入的条件语句会隔离这些字符串,因为它们不符合这个条件。我想创建一个新的字典,其中只有发生相同 TypeError 的 int 值。

有人有什么想法吗?

dictionary = {'a':1, 'b':2, 'c':'letter c', 'd':'letter d'}

for v in dictionary.values():
    if type(v) is int:
        total = sum(v)
        print(total)

【问题讨论】:

    标签: python dictionary for-loop if-statement typeerror


    【解决方案1】:

    在for 循环中执行您正在寻找的事情

    total = 0
    for v in dictionary.values():
        if isinstance(v, int):
            total += v
    

    或者作为生成器表达式

    total = sum(v for v in dictionary.values() if isinstance(v, int))
    

    【讨论】:

      【解决方案2】:

      你想要吗?

      dictionary = {'a':1, 'b':2, 'c':'letter c', 'd':'letter d'}
      
      total = 0
      for v in dictionary.values():
          if type(v) is int:
              total += v
              print(total)
      

      你的问题是你试图调用 sum(int) Sum 用于列表,而不是 sum([1,2,3,5]) = 11

      【讨论】:

        【解决方案3】:

        您误用了 sum 函数。 v 只是一个数字,而不是一个列表,并且 sum 是一个列表的总和。试试这个:

        print(sum(filter(lambda x: type(x) == int, dictionary.values())))
        

        或者这个:

        total = 0
        for v in dictionary.values():
            if type(v) is int:
                total = total + v
        print total 
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-10-07
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多