>>> seq_of_tups = (('a', 1), ('b', 2), ('c', 3))
>>> any(x == 'a' for x, y in seq_of_tups)
True
對於任何大小的元組,你可以使用它代替:
any(x[0] == 'a' for x in seq_of_tups)
這裏也有一些有趣的時刻:
>python -m timeit -s "seq_of_tups = (('a', 1), ('b', 2), ('c', 3))"
"any(x == 'a' for x, y in seq_of_tups)"
1000000 loops, best of 3: 0.564 usec per loop
>python -m timeit -s "seq_of_tups = (('a', 1), ('b', 2), ('c', 3))"
"'a' in (x[0] for x in seq_of_tups)"
1000000 loops, best of 3: 0.526 usec per loop
>python -m timeit -s "seq_of_tups = (('a', 1), ('b', 2), ('c', 3));
from operator import itemgetter; from itertools import imap"
"'a' in imap(itemgetter(0), seq_of_tups)"
1000000 loops, best of 3: 0.343 usec per loop
'>>> 'A' 的zip(* seq_of_tups) FALSE'我想你的意思'拉鍊(* seq_of_tups)[0]' – jamylak 2012-08-12 14:26:40
是啊,哎呀,謝謝 – Ghopper21 2012-08-12 14:31:30