4

2 タプルのシーケンスがあるとします。

seq_of_tups = (('a', 1), ('b', 2), ('c', 3))

'a'シーケンス内の任意のタプルの最初の項目であるかどうかをテストします。

最も Pythonic な方法は何ですか?

辞書に変換してキーをテストすると、どれが理解しやすいでしょうか? すなわち

'a' in dict(seq_of_tups)

あなたがトリックを知らない限り、特に明確ではないかわいいジップトリックを使用しますか? すなわち

'a' in zip(*seq_of_tups)[0]

それともマップで本当に明示的ですか?すなわち

'a' in map(lambda tup: tup[0], seq_of_tups)

または、これらの選択肢のどれよりも良い方法はありますか?

4

2 に答える 2

11
>>> 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
于 2012-08-12T14:24:28.417 に答える
5
>>> 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'
于 2012-08-12T14:29:15.807 に答える