对列表进行排序,删除和附加

时间:2017-10-23 17:00:47

标签: python-3.x list sorting

我正在尝试创建一个程序,允许用户选择是否添加内容,从列表中删除内容或对列表进行排序。但由于某种原因,它不起作用 - 它只是没有排序/删除/添加。 这就是我所拥有的:

countries = ["England", "Germany", "Spain", "Italy", "France", "Turkey", 
  "Greece", "Austria", "America", "Ireland"]
print(countries)
print(" ")

def menu ():
  countries = ["England", "Germany", "Spain", "Italy", "France", "Turkey", 
    "Greece", "Austria", "America", "Ireland"]

  print ("Select the option you require: \n \n 1. Add a new country \n 2. 
    delete a country \n 3. Sort the list \n ")

  option = input("Please enter 1, 2 or 3: ")

  if option == "1":
     addition = input("Enter the country you would like to add: ").title()
     countries = countries.append(addition)

  elif option == "2":
     removes = input("Enter the country you would like to delete").title()

     countries = countries.remove(removes)
  elif option == "3":
     countries.sort()

  else:
     print ("You can only enter 1, 2 or 3 \n")
     menu()

menu()
print(countries)

这是我选择对列表进行排序时控制台产生的内容:

 ['England', 'Germany', 'Spain', 'Italy', 'France', 'Turkey', 'Greece', 
 'Austria', 'America', 'Ireland']

Select the option you require: 

 1. Add a new country 
 2. Delete a country 
 3. Sort the list 

Please enter 1, 2 or 3:  3
['England', 'Germany', 'Spain', 'Italy', 'France', 'Turkey', 'Greece', 
 'Austria', 'America', 'Ireland']

当我期望列表按字母顺序升序排序时。 非常感谢任何帮助,谢谢。

2 个答案:

答案 0 :(得分:1)

您正在对方法菜单中的国家/地区列表进行排序,这对您方法之外的列表没有影响。您可以在排序后打印列表

  elif option == "3":
      countries.sort()
      print(countries)

或删除方法中的列表,您可以将列表移交给方法并返回。

我希望我能帮到你。

答案 1 :(得分:0)

你必须两次定义所有国家的事实告诉你出了问题。您有两个不同的变量,两个名称countries,一个在模块范围内,一个在函数内部。一个便宜而简单的解决方案是使用global关键字使模块级变量可用于函数内部的变异:

countries = ["England", "Germany", "Spain", "Italy", "France", "Turkey", 
  "Greece", "Austria", "America", "Ireland"]
print(countries)
print(" ")

def menu ():
  # Get the countries variable from the module scope
  global countries

  print ("Select the option you require: \n \n 1. Add a new country \n 2. delete a country \n 3. Sort the list \n ")

  option = input("Please enter 1, 2 or 3: ")

  if option == "1":
     addition = input("Enter the country you would like to add: ").title()
     countries = countries.append(addition)

  elif option == "2":
     removes = input("Enter the country you would like to delete").title()

     countries = countries.remove(removes)
  elif option == "3":
     countries.sort()

  else:
     print ("You can only enter 1, 2 or 3 \n")
     menu()

menu()
print(countries)

以这种方式使用全局变量通常被认为是糟糕的风格。相反,请考虑将国家/地区列表作为参数传递给menu函数。