在某个位置插入列表

时间:2016-11-20 23:56:24

标签: python list python-3.x

如何在我创建的列表中的某个位置添加名称?该列表名为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

2 个答案:

答案 0 :(得分:1)

你已经有了一个很好的解决方案。您需要做的第一件事是将您收到的位置转换为整数。你可以这样做:

position = int(position)

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

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

您应该检查此tutorial以了解有关列表的详情。

答案 1 :(得分: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')
相关问题