[英]How do I move my last element in the list to the 3rd position of the list in python?
我想创建一个应该存储在 mylist 下的列表。
#Here is my code.
mylist = [10,20,30,'apple',True,8.10]
mylist
output: [10, 20, 30, 'apple', True, 8.1]
#I want to add two numbers to the list using append()
mylist.append(30)
mylist.append(40)
但是通过两次添加元素,输出如下所示。
mylist
output: [10, 20, 30, 'apple', True, 8.1,30,40,30,40]
然后我想从列表中删除多余的数字 30,40
mylist.remove(40)
mylist.remove(30)
但是我能够删除两个包含 40 和一个 30 的元素
mylist
output: [10, 20, 'apple', True, 8.1, 30]
#现在我想将最后一个元素移动到第三个 position,它应该看起来像下面的 output。
mylist
desired output: [10,20,30,'apple',True, 8.1]
最后,我想使用 append() 将我的两个额外元素 30,40 添加到“mylist”中,而不需要任何重复。
要将最后一个元素移动到第三个 position:
mylist.insert(2, mylist[-1])
mylist.pop(-1)
添加元素:
mylist.append(30)
mylist.append(40)
确保只调用一次 append function。 在调用 append 之前还要检查列表,它还没有 30 和 40。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.