gpt4 book ai didi

python - 如何获取列表列表中的重复项数?

转载 作者:行者123 更新时间:2023-12-01 08:52:18 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com