ここでa を使用して、set
一意のアイテムのみを取得します。
>>> lis = [['welcome','a1'],['welcome','a1'],['hello','a2'],['hello','a3']]
>>> [list(x) + [1] for x in set(map(tuple, lis))]
>>> [['welcome', 'a1', 1], ['hello', 'a3', 1], ['hello', 'a2', 1]]
説明:
Set は常に iterable または iterator から一意の項目を返しますが、set には不変の項目のみを含めることができるため、最初にそれらをタプルに変換する必要があります。上記のコードの冗長バージョン。唯一の違いは、元のコードまたは
>>> lis = [['welcome','a1'],['welcome','a1'],['hello','a2'],['hello','a3']]
>>> s = set()
>>> for item in lis:
... tup = tuple(item) #covert to tuple
... s.add(tup)
>>> s
set([('welcome', 'a1'), ('hello', 'a3'), ('hello', 'a2')])
リスト内包表記を使用して、期待される出力を取得します。
>>> [list(item) + [1] for item in s]
[['welcome', 'a1', 1], ['hello', 'a3', 1], ['hello', 'a2', 1]]
アイテムの順序が重要な場合 (順序をsets
維持しない場合)、これを使用します。
>>> seen = set()
>>> ans = []
>>> for item in lis:
... tup = tuple(item)
... if tup not in seen:
... ans.append(item + [1])
... seen.add(tup)
...
>>> ans
[['welcome', 'a1', 1], ['hello', 'a2', 1], ['hello', 'a3', 1]]
ここで使用する意味がわかりません1
。