如何创建一个在Python中输入空格并删除重复项时停止的列表
我必须创建一个函数,该函数创建一个包含用户给定项的列表,并在给定空间时停止创建列表。然后它必须从此列表中删除重复项。我无法使用内置函数如何创建一个在Python中输入空格并删除重复项时停止的列表,python,Python,我必须创建一个函数,该函数创建一个包含用户给定项的列表,并在给定空间时停止创建列表。然后它必须从此列表中删除重复项。我无法使用内置函数set()。这就是我所拥有的,但是当给一个空格时,会发生TypeError def assignment(): x = input('Type anything') random_list = [] while x != '': x = input("Type anything") random_list.append(x) p
set()
。这就是我所拥有的,但是当给一个空格时,会发生TypeError
def assignment():
x = input('Type anything')
random_list = []
while x != '':
x = input("Type anything")
random_list.append(x)
print(random_list)
x=x+1
for i in random_list:
if i not in random_list:
random_list.append(i)
assignment()
错误是:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 8, in assignment
TypeError: can only concatenate str (not "int") to str
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
分配中第8行的文件“”
TypeError:只能将str(而不是“int”)连接到str
函数input
返回一个字符串,因此变量x
在被赋予input
的返回值时成为一个字符串,并且尝试将整数添加到x+1
的字符串中会产生TypeError
异常
出于您的目的,实际上根本不需要增加x
。删除x=x+1
,并避免在x
为空时将x
附加到随机列表
。在
运算符中使用另一个条件,以避免添加重复项:
while True:
x = input("Type anything")
if x == '':
break
if x not in random_list:
random_list.append(x)
怎么样(在python 2.7和3.6.6下测试)
我认为statemetx=x+1
既没用又有缺陷/
我将您的代码重新排列为:
def assignment():
random_list = []
final_list = []
while True:
x = input("Type anything")
if x!='':
random_list.append(x)
else:
break
for i in random_list:
if i not in final_list:
final_list.append(i)
return final_list
assignment()
什么是x=x+1
?您正在将整数1
添加到字符串x
。这有意义吗?删除x=x+1会更有意义吗?@dude那个类型错误也是因为这个原因cause@dude,如果在那一行之后没有使用x
,那么为什么首先要把它放在那里?这只表明这行代码是无用的,但对您来说,它也会导致异常。所以,是的,你应该删除它。这很有意义。非常感谢。是否可以在此基础上添加删除重复项的功能?
def assignment():
random_list = []
final_list = []
while True:
x = input("Type anything")
if x!='':
random_list.append(x)
else:
break
for i in random_list:
if i not in final_list:
final_list.append(i)
return final_list
assignment()