计算同步列表中项的组合(以字典中的元组形式)

0 投票
1 回答
558 浏览
提问于 2025-04-17 17:18

我有两个列表:

l1 = ['k', 'l', 'k', 's', 'l', 't', 'k']
l2 = ['h', 't', 'h', 't', 't', 's', 's']

我想统计第一个列表中每个位置的项和第二个列表中相同位置的项组合出现的次数。希望得到的结果是:

k-h = 2, l-t = 2, s-t = 1, t-s = 1, k-s = 1

我觉得最好先把这两个列表变成一个元组:

tupleList = zip(l1,l2)
tupeleList = [('k', 'h'), ('l', 't'), ('k', 'h'), ('s', 't'), ('l', 't'), ('t', 's'), ('k', 's')]

然后再创建一个字典来统计这个元组列表中独特元素的数量:

myDict = {}
for item in tupleList:
    if item[1] in myDict:
        myDi [ item[1] ] += item[2]
    else
        myDi [ item[1] ] = item[2]

但是我遇到了这个错误:'元组索引超出范围'。这是什么问题呢?是不是先把列表变成元组效率不高?

1 个回答

7

你可以使用一个叫做 collections.Counter 的工具:

In [7]: import collections
In [10]: count = collections.Counter(zip(l1,l2))

In [11]: count
Out[11]: Counter({('l', 't'): 2, ('k', 'h'): 2, ('s', 't'): 1, ('t', 's'): 1, ('k', 's'): 1})

这个 collections.Counterdict 的一个子类。也就是说,你可以像使用普通的 dict 一样使用它,此外它还有一些额外的功能,比如 elementsmost_commonsubtract 这些方法。


如果你想对你之前发的代码做一些小改动,可以这样写:

l1 = ['k', 'l', 'k', 's', 'l', 't', 'k']
l2 = ['h', 't', 'h', 't', 't', 's', 's']
tupleList = zip(l1,l2)
myDict = {}
for item in tupleList:
    if item in myDict:
        myDict[ item ] += 1
    else:
        myDict[ item ] = 1
print(myDict)       

不过,dict 有一个叫做 get 的方法,可以让你的代码更简单:

for item in tupleList:
    myDict[item] = myDict.get(item, 0) + 1

或者,正如 @JonClements 在评论中提到的,你还可以使用 collections.defaultdict

myDict = collections.defaultdict(int)
for item in tupleList:
    myDict[item] += 1

撰写回答