Unexpected output: Count number of times value appears in nested list & insert it back into list
我有一个嵌套列表,格式为:
1 | [[a1, b1, c1, d1], [a2, b2, c2, d2], [a3, b3, c3, d3]] |
对于每个子列表,我想计算
我已经阅读了这里和这里的线程,并尝试这样做:
1 2 3 4 | 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 |
号
我没有收到任何python错误,但计数一直返回0。所以值"0"一直被插入到我的子列表中,当我清楚地看到实际上在子列表中至少存在一次
以下是屏幕截图:
。
我怀疑我的清单理解错误。有人知道为什么计数不正确吗?
你的问题是:
1 | list_in.count(any(c_umi in s_list for s_list in list_in)) |
要实现这一目标,您可以做如下工作:
1 | u_count = sum(c_umi in s_list for s_list in list_in) |
号
但这将是非常低效的。
你可以更有效地做到这一点。您应该对列表进行一次遍历,并获得一个计数字典,然后在第二遍使用该字典将您的值添加到子列表中(顺便说一下,您应该选择一个比列表更好的容器来用作记录,可能是一个
1 2 3 4 | from collections import Counter counts = Counter(sublist[0] for sublist in list_in) for sublist in list_in: sublist.insert(2, counts[sublist[0]]) |