2016-11-20 93 views
-2

如何将名称添加到我创建的列表中的某个位置?该列表被称为names。如果该位置已被采纳,我想用新名称覆盖该位置。列表中只能有10个名字。在特定位置插入列表

这是代码:

names = [] 
while True: 
    print ('1 = Add Name ') 
    print ('2 = Display List ') 
    print ('3 = Quit \n') 

    choice = input('What would you like to do: ') 
    if choice == '1': 
     number=input('Enter name: ') 
     position= input('What position in the list would you like to add to: ') 
      names.append(name) # what should i do here 
     if(len(names) > 11): 
      print("You cannot enter more names") 
     continue 
    if choice == '2': 
     print(names) 
     continue 
    if choice == '3': 
     print('Program Terminating') 
     break 
    else: 
     print('You have entered something invalid please use numbers from 1-3 ') 
     continue 
+0

我真的不知道你刚刚问了什么。请你能解释一下 –

回答

0

您已经有了一个良好的开端,以解决这一点。你需要做的第一件事是把你收到的位置转换为整数。您可以通过执行此操作:

position = int(position) 

接下来,您将需要在用户输入而不是将其追加到列表的末尾位置插入名称。

因此,将此行更改为names.append(name)names.insert(position, name)。做同样事情的捷径是names[position] = name

您应该检查tutorial以了解更多关于列表的信息。

0

您需要预分配名称列表,以便在所有有效位置可以被索引:

names = ['' for _ in range(10)] 

这样一来,从09列表中的任何有效的索引可以访问和那里的价值已更改:

name = input('Enter name: ') 
position = input('What position in the list would you like to change: ') 
position = int(position) 
if -1 < position < 10: 
    names[position] = name 
else: 
    print('Invalid position entered') 
相关问题