あなたがこれを行うにはcollections.Counter
を使用することができます。私も、前のPython 3.xは存在しなかった、ここで開梱拡張タプルを使用してい
>>> 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の2.xでは、あなたが代わりに行うことができます:
Counter((item[0], item[1]) for item in a)
私は、これはしかし、だろうか、効率的な言うことができませんでした。私はそれが悪いはずだとは思わない。
>>> count = Counter((x, y) for (x, y, *z) in a)
>>> count['309', '308']
2
編集:
Counter
はdict
様な構文を持っているあなたは、彼らができなくなり、この場合には、問題が発生した可能性があり、彼らは、1より大きい任意の長さであるかもしれない言及しました必要な長さよりも短い場合は解凍してください。
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)
最後のタプルに4つの数字があったのでしょうか? –
はい。これは私の例のように> 1、3、4のいずれの数字でもかまいません。 – Learnerbeaver