11
>>> a= ('one', 'a')
>>> b = ('two', 'b')
>>> c = ('three', 'a')
>>> l = [a, b, c]
>>> l
[('one', 'a'), ('two', 'b'), ('three', 'a')]

一意の 2 番目のエントリ (列?項目?) を持つこのリストの要素のみをチェックし、リストで見つかった最初のエントリを取得するにはどうすればよいですか。望ましい出力は

>>> l
[('one', 'a'), ('two', 'b')]
4

2 に答える 2

16

セットを使用します (2 番目のアイテムがハッシュ可能な場合):

>>> lis = [('one', 'a'), ('two', 'b'), ('three', 'a')]
>>> seen = set()
>>> [item for item in lis if item[1] not in seen and not seen.add(item[1])]
[('one', 'a'), ('two', 'b')]

上記のコードは次と同等です。

>>> seen = set()
>>> ans = []
for item in lis:
    if item[1] not in seen:
        ans.append(item)
        seen.add(item[1])
...         
>>> ans
[('one', 'a'), ('two', 'b')]
于 2013-09-05T19:10:48.773 に答える