确定列表中有多少对

时间:2015-03-25 15:38:52

标签: python list

假设我有一个包含x对的n个整数的列表,例如:

list = [1, 2, 7, 2, 4, 4, 5, 6]
#Two pairs in total, 2 and 4

确定list

中有多少对的最简单方法是什么?

2 个答案:

答案 0 :(得分:3)

您可以在列表理解和list.count中使用set

>>> l = [1, 2, 7, 2, 4, 4, 5, 6]
>>> set([i for i in l if l.count(i)==2])
set([2, 4])

collections.Counter的基准:

~$ python -m timeit "from collections import Counter; l= [1, 2, 7, 2, 4, 4, 5, 6];set([i for i,j in Counter(l).items() if j==2])"
100000 loops, best of 3: 8.65 usec per loop
:~$ python -m timeit " l= [1, 2, 7, 2, 4, 4, 5, 6];set([i for i in l if l.count(i)==2])"
1000000 loops, best of 3: 1.38 usec per loop

答案 1 :(得分:0)

要确定元素是否存在多次,您可以执行以下操作:

a = [1, 2, 3, 1, 2, 3, 4, 5, 6, 7, 7, 7]
b = set(a)
print len (a) - len (b), " elements are present more than one time"

打印哪些:

 5  elements are present more than one time

要确定对的数量,您可以这样做:

a = [1, 2, 3, 1, 2, 3, 4, 5, 6, 7, 7, 7]
b = {}
for i in a:
    if i in b:
        b[i] += 1
    else :
        b[i] = 1

print len ([x for x in b if b[x] == 2]), " elements are pairs"