简体   繁体   English

在列表中的特定位置插入元素

[英]Insert an element at specific place in a list

i have a problem using list.insert method. 我在使用list.insert方法时遇到问题。 You can see my code below. 您可以在下面看到我的代码。

z=[1,9,6,5,5,3,4,6]
y=['1','4','9','7','6','5','5','1','5','0','3','3','4','1','6','0']
z.insert(z[0],int(y[1]))
print(z)
[1, 4, 9, 6, 5, 5, 3, 4, 6]
z.insert(z[2],int(y[3]))
print(z)
[1, 4, 9, 6, 5, 5, 3, 4, 6, 7]

Why does 7 go after 6 and not after 9???? 为什么7在6之后而不是9之后???? Thanks in advance!! 提前致谢!!

z[2] is 9 . z[2]9

[1, 4, 9, 6, 5, 5, 3, 4, 6]
       ^

You move it to the 9th index (after 6 ). 您将其移到第9个索引(在6之后)。

z=[1,9,6,5,5,3,4,6]
y=['1','4','9','7','6','5','5','1','5','0','3','3','4','1','6','0']
z.insert(z[0],int(y[1]))  #grabs 1 from z, and 4 from y
print(z)
[1, 4, 9, 6, 5, 5, 3, 4, 6]
z.insert(z[2],int(y[3]))  #grabs index 2 from z which is 9, 
                          #and insert will insert into the last element 
                          #if the index is out of range
print(z)
[1, 4, 9, 6, 5, 5, 3, 4, 6, 7]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM