计算列表中出现的组合数量

时间:2014-11-27 16:08:38

标签: python list

我通过这样做创建了一个列表:

list3= [zip(Indiener1, Indiener2)]

这两个元素都是长名单。

但作为小组合列表中的第三个元素,我想要在整个list3中出现名称组合的次数,因为我必须使用该数字进行计算。

我尝试了list3.count(),但该功能只想拍摄一件物品。

我该怎么做?

3 个答案:

答案 0 :(得分:1)

from collections import Counter

list1=["a","b","d","b"]
list2=["5","u","55","u"]
list3=zip(list1,list2)

print Counter(list3)

输出:

Counter({('b', 'u'): 2, ('d', '55'): 1, ('a', '5'): 1})

答案 1 :(得分:0)

使用计数器并反转配对以获得("foo","bar") == ("bar","foo")

 l1 =["foo","bar","foobar"]
l2 = ["bar","foo","bar"]

from collections import Counter
c = Counter(zip(l1,l2))

for k,v in c.items():
    rev = tuple(reversed(k))
    print("pairing {}  appears {}".format(k,v + c.get(rev,0)))

为避免获得双倍输出('foo', 'bar')('bar', 'foo'),您可以将rev添加到集合中,并检查它是否已被查看:

from collections import Counter
c = Counter(zip(l1,l2))
seen = set()
for k, v in c.items():
    rev = tuple(reversed(k))
    if k not in seen:
        seen.add(rev)
        print("pairing {}  appears {} times".format(k,v + c.get(rev,0)))

pairing ('foo', 'bar')  appears 2 times
pairing ('foobar', 'bar')  appears 1 times

答案 2 :(得分:0)

由于("foo","bar")("bar","foo")被视为相同,因此您必须指望sets之类的内容,其中顺序无关紧要:

>>> from collections import Counter
>>> l1 = ['John', 'Doe', 'Paul', 'Pablo', 'Paul', 'Doe']
>>> l2 = ['Doe', 'John', 'Doe', 'Doe', 'Doe', 'Paul']
>>> print Counter(frozenset(pair) for pair in zip(l1, l2))
Counter({
    frozenset(['Paul', 'Doe']): 3, 
    frozenset(['John', 'Doe']): 2, 
    frozenset(['Doe', 'Pablo']): 1
})

您还可以在计数之前对对进行排序,但set可以使目的更明确。