[英]How do you get this to remove the value that the user wants to remove from the list and then return the new list values
def main():
values = []
numbers = get_Values(values)
print("The numbers in the list are:")
print(numbers)
removeList = remove_Value_List(values)
print(removeList)
def get_Values(values): #This asks the user to enter all the values they want to be in the list
again = "y"
while again == "y":
num = float(input("Enter a number:"))
values.append(num)
print("Do you want to add another number?")
again = input("y = yes, anything else = no:")
print()
return values
def remove_Value_List(values): #This asks the user which value they want to remove from the list
print("Here are the numbers in the list:")
print(values)
number_list = input("Which value should I remove?")
try:
values.remove(number_list)
print("Here is the revised list:")
return values
except ValueError:
print("That item is not found in the list.")
number_list = input("which value should I remove?")
main()
您如何获取此信息以将用户想要从列表中删除的值删除,然后返回新的列表值?
num = float(input("Enter a number:"))
values.append(num)
将数字添加到列表时,会将其转换为浮点数。
number_list = input("Which value should I remove?")
values.remove(number_list)
当您尝试删除它们时,您没有进行浮点转换,因此它将尝试删除用户键入的字符串。 这将永远不会删除任何内容,因为列表不包含字符串。
如果您确实要在函数中进行删除,则需要执行循环。 否则,except将变为无。 我看到,一旦删除一个值,该操作就会退出。 我会假设这就是您想要的方式。
def remove_Value_List(values):
#This asks the user which value they want to remove from the list
print("Here are the numbers in the list:")
print(values)
# Now ask which numbers to remove
while True:
try:
number_list = input("Which value should I remove?")
values.remove(number_list)
print("Here is the revised list:")
return values # You can use break here
except ValueError:
print("That item is not found in the list.")
continue
# If you used break in the while put return values here
# return values if break was used to exit the loop
但是,还有另一种方法。 您为创建两个列表的函数设置了两个定义。 您应该使该函数具有创建删除列表(remove_Value_List())的功能,与创建编号列表(get_Values())的方法相同。 您不应该检查删除列表中的成员是否在数字列表中,因为它们是独立的功能,您稍后可以在数字列表中添加一些内容。 您应该编写两个函数以单独运行。
完全构建了两个列表之后, 然后遍历remove_List并重做数字列表。 如果要将此清除列表作为第三列表,而不是更改数字,请首先进行复制
newnumbers = numbers[:]
for x in removeList:
if x in newnumbers:
newnumbers.remove(x)
当然,您也可以使用try:except方法,但是上面避免了。
newnumbers = numbers[:]
for x in removeList:
try:
newnumbers.remove(x)
except ValueError:
continue
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.