我正在创建一个功能,通过删除重复项来缩短列表。我一直在摆弄代码一段时间,每当我摆脱一个错误时,我就会得到另一个错误。有什么想法吗?
def delete_adjacent():
user_list = []
list_length = int(input("How long do you want your list? "))
check = 0
characters = ""
while len(user_list) != list_length:
new_item = input("Input your item for the list: ")
user_list.append(new_item)
print (user_list)
while check != list_length:
item = user_list[check]
count = user_list.count(item)
if count == 1:
check += 1
while count > 1:
user_list.remove(item)
return
delete_adjacent()
答案 0 :(得分:1)
只需使用set
set
是一个像list
一样的对象,没有重复项。
user_list = list(set(user_list))
您可以将list
转换为set
以删除重复内容,然后将其转换回list
以免影响代码流
答案 1 :(得分:0)
感谢“无花果”,我找到了最简单的方法。
def delete_adjacent():
user_list = []
list_length = int(input("How long do you want your list? "))
characters = ""
while len(user_list) != list_length:
new_item = input("Input your item for the list: ")
user_list.append(new_item)
print(set(user_list))
return
delete_adjacent()
答案 2 :(得分:0)
我想你想这样:
>>> def remove_dup():
... user_list = []
... list_length = int(input("how long do you want your list? :"))
... while len(user_list) < list_length:
... item = input("enter a item: ")
... if item != "" and item not in user_list:
... user_list.append(item)
... else: print "Either item was null or was already present in list"
... return user_list
...
>>> remove_dup()
how long do you want your list? :4
enter a item: 1
enter a item: 3
enter a item: 1
Either item was null or was already present in list
enter a item: 4
enter a item: 6
[1, 3, 4, 6]