意外输出:计数值出现在嵌套列表中的值&将其插回到列表中

时间:2018-02-05 18:12:28

标签: python list count nested

我有一个嵌套列表格式:

[[a1, b1, c1, d1], [a2, b2, c2, d2], [a3, b3, c3, d3]]

对于每个子列表,我想计算a (a1, a2, a3, ...)出现在任何子列表中的次数(自{{1}以来}可能会出现在多个子列表中),然后将其插回到我正在迭代的当前子列表中。

我已经阅读了帖子herehere,并尝试这样做:

a

我没有得到任何python错误,但是计数一直返回0.所以值“0”不断插入我的子列表,当我可以清楚地看到时事实for sl in list_in: # Iterate through each sub-list in the big list c_umi = sl[0] # "c_umi" is "a" in my example above; i.e. extract each "a" value from the big list u_count = list_in.count(any(c_umi in s_list for s_list in list_in)) # Count the number of times "c_umi" appears in any of the sub-lists in the entire big list, not just the sub-list I'm iterating over at the moment sl.insert(2, u_count) # Insert the count into index #2 of the current sub-list 在子列表中至少存在一次!

以下是截图:

"u_count" is 0, but I definitely have at least 1 value in "list_in"

我怀疑我的列表理解是不正确的。有谁知道为什么这不正确?

1 个答案:

答案 0 :(得分:2)

你的问题是:

any

list_in总是返回一个布尔值,永远不会在list 中,它完全由bool个对象组成。 list永远不会等于u_count = sum(c_umi in s_list for s_list in list_in) ,这就是你总是得到0的原因。

为了完成这项工作,您可以做类似的事情:

namedtuple

但这将是非常低效的。

你可以更有效地做到这一点。您应该对列表进行一次传递并获取计数字典,并在第二次传递中使用该字典将您的值添加到子列表中(另外,您应该选择比列表更好的容器作为记录,或许.insertfrom collections import Counter counts = Counter(sublist[0] for sublist in list_in) for sublist in list_in: sublist.insert(2, counts[sublist[0]]) 进入列表效率低下,但由于你的子列表很小,可能不是什么大问题......)。

BorderStyle = bsNone