[英]What is the most Pythonic way to test for match with first item of tuple in sequence of 2-tuples?
假設你有一系列2元組:
seq_of_tups = (('a', 1), ('b', 2), ('c', 3))
並且您想測試'a'
是否是序列中任何元組的第一項。
什么是最恐怖的方式?
轉換為字典並測試密鑰,這似乎很容易理解? 即
'a' in dict(seq_of_tups)
使用可愛的拉鏈技巧,除非你知道這個技巧,否則不是特別清楚? 即
'a' in zip(*seq_of_tups)[0]
或者真的明確地圖? 即
'a' in map(lambda tup: tup[0], seq_of_tups)
還是有比這些選擇更好的方法?
>>> 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
>>> tups = (('a', 1), ('b', 2), ('c', 3))
>>> 'a' in (x[0] for x in tups)
True
>>> 'd' in (x[0] for x in tups)
False
上述解決方案將盡快退出a
被發現,證明:
>>> tups = (('a', 1),('a',5), ('b', 2), ('c', 3))
>>> gen=(x[0] for x in tups)
>>> 'a' in gen
True
>>> list(gen)
['a', 'b', 'c'] #this result means generator stopped at first 'a'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.