列表推导式提供了一种创建列表的简洁方法。常见的
应用程序将创建新列表,其中每个元素都是以下结果的结果
某些操作应用于另一个序列的每个成员或
可迭代,或者创建满足 a 的元素的子序列
一定的条件。
也许你可以尝试这个:
>>> 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]
Notice:
append()
回报None
如果插入操作成功。
另一种方法,您可以尝试使用set
删除重复项:
>>> a = ['It', 'is', 'the', 'east', 'and', 'Juliet', 'is', 'the', 'sun']
>>> list(set(a))
['and', 'sun', 'is', 'It', 'the', 'east', 'Juliet']