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

标签 python python-3.x

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/

相关文章:

python - 使用 xlwt 将数组从特定列开始写入新工作簿

python - 解决 python 中的 lambda 限制

python - 如果我重用它们,我应该缓存范围结果吗?

python - 识别数组中的相似实例并合并它们

python - 在 Mac OS X 上,easy_install fabric 和/或 easy_install pycrypto 由于链接器错误 "illegal text-relocation"而失败

python - Abaqus python 脚本 - 在 .mdb 中创建的元素集无法在 .odb 中访问

能够进行分块传输编码的 Python Web 框架?

python - click.Choice 多个参数

python-3.x - 从 Python 访问 COM 方法

python - 将新字典添加到现有字典中作为键的值