Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jsf-2/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将名称添加到列表中的特定位置_Python_List - Fatal编程技术网

Python 将名称添加到列表中的特定位置

Python 将名称添加到列表中的特定位置,python,list,Python,List,如何让我的代码向用户要求的列表中的某个位置(列表中只能有10个名称)添加一个名称,如下所示: print (names) [,,,Bob,,,,,,] #in my code names = [] name=input('what name would you like to enter?') Bob pos=input(what position in the list would you like to add to(1-10)?') 在这句话之后,我该怎么办?首先,为了引用列表中的索

如何让我的代码向用户要求的列表中的某个位置(列表中只能有10个名称)添加一个名称,如下所示:

print (names)
[,,,Bob,,,,,,]

#in my code
names = [] 
name=input('what name would you like to enter?') Bob
pos=input(what position in the list would you like to add to(1-10)?')

在这句话之后,我该怎么办?首先,为了引用列表中的索引,该索引必须存在。因此,初始化列表:

names=[None]*10
然后,收集您的输入:

name=input('what name would you like to enter?')
pos=input('what position in the list would you like to add to(1-10)?')
由于
pos
将被收集为
str
对象,您必须将其转换为数字并减去一,因为您从1开始索引,Python从0开始索引

names[int(pos)-1]=name

您需要首先学习如何a)对列表进行切片,然后b)将多个列表附加在一起。关于这两个主题的信息已经非常丰富了。任何Python教程都会向您展示如何在指定的列表索引处设置该项。请注意,
[,,,Bob,,,,,]
并不是真正有效的,但类似于
[None,None,'Bob',None]
的内容将是。
名称。插入(pos,Bob)
名称[pos]=Bob
。但是,接受@jornsharpe的建议,读一本像样的教程。它会比我们更有用。