Python
我有一个列表列表。喜欢
A = [[x,y],[a,b],[c,f],[e,f],[a,b],[x,y]]
Run Code Online (Sandbox Code Playgroud)
我想计算每个列表在主列表中出现的次数。
我的输出应该像
[x,y] = 2
[a,b] = 2
[c,f] = 1
[e,f] = 1
Run Code Online (Sandbox Code Playgroud)
只需使用Counter来自collections:
from collections import Counter
A = [[x,y],[a,b],[c,f],[e,f],[a,b],[x,y]]
new_A = map(tuple, A) #must convert to tuple because list is an unhashable type
final_count = Counter(new_A)
#final output:
for i in set(A):
print i, "=", final_count(tuple(i))
Run Code Online (Sandbox Code Playgroud)
您可以使用collections.Counter- 一个 dict 子类 - 来计算。首先,将子列表转换为元组,使它们可用作(即可散列)作为字典键,然后计数:
from collections import Counter
count = Counter(map(tuple, A))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10439 次 |
| 最近记录: |