完全不熟悉Python,所以请耐心等待。
我通过raw_input创建了一个列表:
itemList = []
num = int (raw_input("Enter a number: "))
for i in range (num):
listStr = raw_input("Enter an item: ")
itemList.append (listStr)
现在我必须检查是否有任何项目,以及是否确实要求另一个raw_input添加到列表中。我完全难过了。这不是循环的;它只是打印一个。我还必须将新项目附加到原始列表。难住了。
itemList = []
num = int (raw_input("Enter a number: "))
for i in range (num):
listStr = raw_input("Enter an item: ")
itemList.append (listStr)
for a in itemList:
if a in itemList :
a = raw_input("Enter another number: ")
答案 0 :(得分:0)
您可以使用while
循环继续询问输入,直到输入的项目已经不在列表中。这可以改进,但它应该让你开始:
itemList = []
num = int (raw_input("Enter a number: "))
for i in range (num):
while True:
listStr = raw_input("Enter an item: ")
if listStr in itemList:
print('That item is already in the list')
else:
itemList.append(listStr)
break
稍微好一点的版本:
itemList = []
num = int(raw_input("Enter a number: "))
for i in range(num):
listStr = raw_input("Enter an item: ")
while listStr in itemList:
print("That item already exists")
listStr = raw_input("Enter another number: ")
itemList.append(listStr)
答案 1 :(得分:-1)
以下是代码的略微修改版本
itemList = []
num = int (raw_input("Enter a number: "))
for i in range (num):
listStr = raw_input("Enter an item: ")
itemList.append (listStr)
for idx in range(len(itemList)):
# using a while ensures that if the value newly entered
# is again present in the list, it again prompts for an input
while itemList[idx] in itemList[:idx] or itemList[idx] in itemList[idx+1:] :
a = raw_input("Enter a replacement for item {0}: ".format(itemList[idx]))
itemList[idx] = a