我有一些語法:如何在Python中減少列表推導的行數?
l_one = [ x for x in someList ] # list with duplicates
l = []
l_two = [ l.append(y) for y in l_one if y not in l ] # duplicates removed
L和l_two是沒有重複相同的列表。是否有減少線條的方法,並可能有再版?
編輯: 更正 - l_two是「Noned」列表。
我有一些語法:如何在Python中減少列表推導的行數?
l_one = [ x for x in someList ] # list with duplicates
l = []
l_two = [ l.append(y) for y in l_one if y not in l ] # duplicates removed
L和l_two是沒有重複相同的列表。是否有減少線條的方法,並可能有再版?
編輯: 更正 - l_two是「Noned」列表。
其實它們是不一樣的。 .append()
返回None
,因爲它修改了位置列表,所以l_two
是一列None
s的列表。但是,l
將成爲沒有任何愚蠢的名單。
如果你想從列表中刪除重複的,你可以把它轉換爲一組:
l_two = list(set(l_one))
注意,這將刪除訂單。
使用一個for循環,而不是一個列表理解,如果你想使用unhashable類型的嘗試:
l_one = [x for x in someList]
l_two = []
for i in l_one:
if i not in l_two:
l_two.append(i)
或者:如果我理解正確
from itertools import groupby
l_two = [key for key, value in groupby(l_one)]
,你從名爲someList
的列表開始,它可能有重複的內容,並且您希望以相同的列表結束,但刪除了重複項?
您可以通過刪除您的第一行代碼,這只是複製someList到一個新的(但相同)列表稱爲l_one開始:
>>> someList = [ 3,1,4,1,5,9,2,7 ]
>>> l = []
>>> [ l.append(y) for y in someList if y not in l]
[None, None, None, None, None, None, None]
>>> print l
[3, 1, 4, 5, 9, 2, 7]
>>>
這個工程即使someList的元素本身列出:
>>> l = []
>>> someList = [[1,2],[2,1],[1,2],[3,4]]
>>> l = []
>>> [ l.append(y) for y in someList if y not in l]
[None, None, None]
>>> print l
[[1, 2], [2, 1], [3, 4]]
>>>
請檢查[如何從列表中刪除重複項](http://docs.python.org/3/faq/programming.html#how-do-you-remove-duplicates-from-a-列表)。 – zhangyangyu