我正在尝试从python删除重复的单词,一切正常,但是“ Kate”单词仍然重复。救救我
def custom_function(list):
sia = []
for item in list:
sia.append(item.capitalize())
for word in sia:
while sia.count(word) != 1:
sia.remove(word)
if sia.count(word) == 1:
break
return sia
unknown_list = ["toby", "James", "kate", "George", "James", "rick", "Alex",
"Jein", "Alex", "Alex","George", "Jein", "kate", "medelin"]
print(custom_function(unknown_list))
答案 0 :(得分:0)
请不要更改您要遍历的容器。而是创建一个新的临时列表并分配回来:
>>> unknown_list = ["toby", "James", "kate", "George", "James", "rick", "Alex",
"Jein", "Alex", "Alex","George", "Jein", "kate", "medelin"]
>>> def uniquefy(my_lst):
temp = []
for x in my_lst:
if x not in temp:
temp.append(x)
return temp
>>> uniquefy(unknown_list)
['toby', 'James', 'kate', 'George', 'rick', 'Alex', 'Jein', 'medelin']
答案 1 :(得分:0)
您可以使用列表copy()方法执行以下操作:
def custom_function(list):
sia = []
for item in list:
sia.append(item.capitalize())
sia_orig = sia.copy()
for word in sia_orig:
while True:
if sia.count(word) != 1:
sia.remove(word)
if sia.count(word) == 1:
break
else:
break
return sia
unknown_list = ["toby", "James", "kate", "George", "James", "rick", "Alex",
"Jein", "Alex", "Alex","George", "Jein", "kate", "medelin"]
print(custom_function(unknown_list))
输出:
['Toby', 'James', 'Rick', 'Alex', 'George', 'Jein', 'Kate', 'Medelin']