回覆列表
-
1 # 使用者9080162693404
-
2 # 使用者2062070693800
程式碼如下:
oldList = ["a","b","c","d","a","a"]
newList = []
for letter in oldList:
if letter not in newList:
newList.append(letter)
print newList
執行結果:
["a", "b", "c", "d"]
使用列表推導,只保留元素個數等於1的
a = ["a", "b", "c", "d", "a", "a"]b = [x for x in a if a.count(x) == 1]print b
列表推導中的x for x in a if a.count(1) == 1和下面的for迴圈等價,不過更簡潔:
b = []for x in a: if a.count(x) == 1: b.append(x)print b