作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
a=[[2, 5, 21,],
[2, 9, 14,],
[2, 22, 32],
[3, 10, 13],
[3, 10, 13]
[3, 10, 13]]
for i in range(len(a)):
cnt=1 #count
for j in range(i, len(a)):
if (i==j):
continue
elif (len(set(a[i])&set(a[j]))==6):
cnt+=1
print('\t{:2} {:2} {:2} {:2} {:2} {:2}, number {:2} '.format(*a[i],cnt))
else:
pass
我要创建的代码如下
[3, 10, 13], num 3
如何统计列表中的列表?
最佳答案
您可以使用collections.Counter如果将内部列表转换为元组(list
不可散列 - dict
需要可散列键 - 例如 tuples
):
from collections import Counter
a=[[2, 5, 21,],
[2, 9, 14,],
[2, 22, 32],
[3, 10, 13],
[3, 10, 13],
[3, 10, 13]]
c = Counter( map(tuple,a) ) # shorter notation for: ( tuple(item) for item in a) )
# extract all (key,value) tuples with values > 1
for what, how_much in (x for x in c.most_common() if x[1] > 1):
# 3.6 string interpol, use "{} num {}".format(list(what),how_much) else
print(f"{list(what)} num {how_much}")
输出:
[3, 10, 13] num 3
<小时/>
您还可以使用 itertools.groupby()但您必须先对列表进行排序:
import itertools
# to make groupby work
a.sort()
for key,items in itertools.groupby(a):
how_much = len(list(items))
if how_much > 1:
print(key, "num", how_much)
相同的结果。 itertools 的使用大致受到 this answer 的启发。寻找此OP的骗局时“如何从列表列表中删除骗局”)
关于python - 如何获取列表列表中的重复项数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53032949/
如何计算 json feed 中的项目数量? 缩写的 json 格式... { "rlm1":[...], "rlm2":[...], "rlm3":[...], "r
我是一名优秀的程序员,十分优秀!