Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.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_Class_Methods_Insert - Fatal编程技术网

使用python插入方法的挑战

使用python插入方法的挑战,python,list,class,methods,insert,Python,List,Class,Methods,Insert,我正在尝试一些python列表练习问题。我试图在索引“-1”处插入一个新名称mike,但在将输出打印到屏幕上时,我注意到它默认位于晚餐列表中的另一个位置(索引(-2)) dinner = ['yemi', 'bimpe', 'kola', 'kunle', 'bola', 'shola', 'ola'] invite = f"{dinner[0].title()}, would you be available to attend our dinner party?" pr

我正在尝试一些python列表练习问题。我试图在索引“-1”处插入一个新名称mike,但在将输出打印到屏幕上时,我注意到它默认位于晚餐列表中的另一个位置(索引(-2))

dinner = ['yemi', 'bimpe', 'kola', 'kunle', 'bola', 'shola', 'ola']

invite = f"{dinner[0].title()}, would you be available to attend our dinner party?"
print(invite)

invite = f"{dinner[-1].title()}, would you be available to attend our dinner party?"
print(invite)

invite = f"{dinner[-3].title()}, would you be available to attend our dinner party?"
print(invite)

invite = f"{dinner[3].title()}, would you be available to attend our dinner party?"
print(invite)

invite = f"{dinner[1].title()}, would you be available to attend our dinner party?"
print(invite)

not_coming = f"{dinner[0].title()} said she can't make the dinner party tonight and has to be swapped with {dinner[1].title()}"
print(not_coming)

not_coming = f"{dinner[-1].title()} said she can't make the dinner party tonight and has to be swapped with {dinner[-2].title()}"
print(not_coming)

dinner.insert(0, "kingsley")
print(dinner)

dinner.insert(-1, "mike")
print(dinner)
为什么会这样

名单上的名字是“晚餐” 国家文件

在给定位置插入项目。第一个参数是要插入的元素的索引

因此,如果使用索引
-1
,它将在最后一个之前插入


若要插入最后一个,请使用以下任一选项

dinner.insert(len(dinner), "mike")
dinner.append("mike")

非常感谢。我现在明白了。@yappiesam你可以考虑接受这个答案;)