您可以使用它collections.Counter
来执行此操作:
>>> from collections import Counter
>>> a = ( ('309','308','308'), ('309','308','307'), ('308', '309','306', '304'))
>>> Counter((x, y) for (x, y, *z) in a)
Counter({('309', '308'): 2, ('308', '309'): 1})
>>> Counter((x, z) for (x, y, z, *w) in a)
Counter({('308', '306'): 1, ('309', '308'): 1, ('309', '307'): 1})
我在这里也使用了扩展元组解包,它在 Python 3.x 之前不存在,只有当你有不确定长度的元组时才需要它。在 python 2.x 中,您可以改为:
Counter((item[0], item[1]) for item in a)
但是,我不能说这会有多有效。我不相信它应该是坏的。
ACounter
有一个类似dict
的语法:
>>> count = Counter((x, y) for (x, y, *z) in a)
>>> count['309', '308']
2
编辑:您提到它们的长度可能大于一,在这种情况下,您可能会遇到问题,因为如果它们短于所需长度,它们将无法解包。解决方案是更改生成器表达式以忽略任何不符合要求的格式:
Counter((item[0], item[1]) for item in a if len(item) >= 2)
例如:
>>> a = ( ('309',), ('309','308','308'), ('309','308','307'), ('308', '309','306', '304'))
>>> Counter((x, y) for (x, y, *z) in a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.2/collections.py", line 460, in __init__
self.update(iterable, **kwds)
File "/usr/lib/python3.2/collections.py", line 540, in update
_count_elements(self, iterable)
File "<stdin>", line 1, in <genexpr>
ValueError: need more than 1 value to unpack
>>> Counter((item[0], item[1]) for item in a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.2/collections.py", line 460, in __init__
self.update(iterable, **kwds)
File "/usr/lib/python3.2/collections.py", line 540, in update
_count_elements(self, iterable)
File "<stdin>", line 1, in <genexpr>
IndexError: tuple index out of range
>>> Counter((item[0], item[1]) for item in a if len(item) >= 2)
Counter({('309', '308'): 2, ('308', '309'): 1})
如果您需要可变长度计数,最简单的方法是使用列表切片:
start = 0
end = 2
Counter(item[start:end] for item in a if len(item) >= start+end)
当然,这只适用于连续运行,如果你想单独选择列,你必须做更多的工作:
def pick(seq, indices):
return tuple([seq[i] for i in indices])
columns = [1, 3]
maximum = max(columns)
Counter(pick(item, columns) for item in a if len(item) > maximum)