2017-04-01 19 views
-1

あるリストから別のリストにユニークなアイテムを入れたい、つまり重複するアイテムを削除したい。私が長い方法でそれをすると、私はそれを行うことができます例えば、参照してください。リストの理解が機能しない

>>>new_list = [] 
>>>a = ['It', 'is', 'the', 'east', 'and', 'Juliet', 'is', 'the', 'sun'] 

>>> for word in a: 
    if word not in a: 
     new_list.append(word) 

>>> new_list 
['It', 'is', 'the', 'east', 'and', 'Juliet', 'sun'] 

しかし、試して、単一の行にインクルード各反復戻り値を使用してこのリスト内包を達成するために、「なし」

>>> new_list = [] 
>>> a = ['It', 'is', 'the', 'east', 'and', 'Juliet', 'is', 'the', 'sun'] 
>>> new_list = [new_list.append(word) for word in a if word not in new_list] 

誰かがリストの内包に間違っていただきまし理解する上で助けてください。事前に

おかげで Umesh

+1

'それがリストに追加されたものですので、' NONE'を返しappend'。あなたはリスト内包表記を見直す必要があると思います。 – Carcigenicate

+0

私はあなたが 'new_list'にはない単語を意味し、' not in a'を意味しないと思います。 – TigerhawkT3

答えて

0

あなたは言葉のユニークなリストが必要な場合は、set()を使用することができます。

list(set(a)) 
# returns: 
# ['It', 'is', 'east', 'and', 'the', 'sun', 'Juliet'] 

順序が重要な場合は、試してみてください。

new_list = [] 
for word in a: 
    if not a in new_list: 
     new_list.append(word) 
1

リストの内包表記はリストを作成するための簡潔な方法を提供します。共通 アプリケーションでは、各要素が別のシーケンスの各メンバーに適用された の操作または の反復の結果である新しいリストを作成するか、 の条件を満たす要素のサブシーケンスを作成する必要があります。

たぶん、あなたはこれを試すことができます。

>>> new_list = [] 
>>> a = ['It', 'is', 'the', 'east', 'and', 'Juliet', 'is', 'the', 'sun'] 
>>> unused=[new_list.append(word) for word in a if word not in new_list] 
>>> new_list 
['It', 'is', 'the', 'east', 'and', 'Juliet', 'sun'] 
>>> unused 
[None, None, None, None, None, None, None] 

お知らせ:

append()戻りNoneを挿入操作が成功した場合。

もう一つの方法は、重複した項目を削除するsetを使用しようとすることができます

>>> a = ['It', 'is', 'the', 'east', 'and', 'Juliet', 'is', 'the', 'sun'] 
>>> list(set(a)) 
['and', 'sun', 'is', 'It', 'the', 'east', 'Juliet'] 
+0

速い答え。私はほとんど同じことを書いています。 +1 –

関連する問題