如何通过删除用户想要从列表中删除的值,然后返回新的列表值

时间:2014-03-04 20:59:11

标签: python

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()

如何删除用户想要从列表中删除的值,然后返回新的列表值?

2 个答案:

答案 0 :(得分:2)

num = float(input("Enter a number:"))
values.append(num)

将数字添加到列表时,将它们转换为浮点数。

number_list = input("Which value should I remove?")
values.remove(number_list)

当您尝试删除它们时,您没有浮点转换,因此它会尝试删除用户键入的字符串。由于列表不包含字符串,因此永远不会删除任何内容。

答案 1 :(得分:0)

如果你真的想在函数中删除,那么你需要做一个循环。否则,除非将返回无。我看到,一旦删除了一个值,就会退出。我会认为这就是你想要的方式。

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    

然而,还有另一种方法可以做到这一点。您为函数设置了两个定义以创建两个列表。您应该使用与创建数字列表(get_Values())相同的方式创建删除列表(remove_Value_List())。您不应该检查删除列表的成员是否在数字列表中,因为这些是独立的功能,您可以稍后在数字列表中添加一些内容。你应该把这两个函数写成自己运行。

完成两个列表的构建后,然后执行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