使用 'for loop' 对嵌套列表值求和,并使用 return(总和)

Using 'for loop' to sum nested list values and return (total of sum)

我正在接收每个列表中每一行的计数, 我希望对整个列表的每个特定值求和,(包括嵌套列表)

[[3],[4],][1],[3]] = * 11 是我想要的结果。

示例: 代码

ar1 = [
          ['jam','apple','pear'],
          ['toes','tail','pinky','liar'],
          ['aha!'],
          ['jam','apple','pear']
      ]

def function(arg1)
    heads = 0
    for i in arg1:
        heads += arg1.count(i)
        print heads

我用过这个print因为除了打印语句和重新检查工作我不知道如何编译和调试其他任何东西,所以请不要发火。(新手警报)

示例: 结果

['jam','apple','pear']     1
['toes','tail','pinky','liar']    2
['aha!']     3
['jam','apple','pear']    4

我更喜欢提示,或提示我应该应用什么方法或示例。我绝不期待解决方案。我

您有一些选择:

1.flatten 您的嵌套列表并计算总列表的长度:

>>> len(reduce(lambda x,y:x+y,ar1))
11

或者您可以遍历您的列表并对所有子列表的长度求和,您可以使用 sum 函数中的生成器表达式来完成:

>>> sum(len(i) for i in ar1)
11

如果您的实际数据包含比您显示的更深的嵌套:

def sum_len(lst):
    return sum(1 if not isinstance(e, list) else sum_len(e) for e in lst)

ar1 = [
          ['jam','apple','pear'],
          ['toes','tail','pinky','liar'],
          ['aha!'],
          ['jam','apple','pear']
      ]
print sum_len(ar1)  # 11

# Same elements, with arbitrary list wrapping:
ar2 = [
          [['jam','apple',['pear']]],
          [['toes',['tail','pinky'],'liar']],
          [['aha!']],
          [[['jam','apple'],'pear']]
      ]
print sum_len(ar2)  # 11