[英]List with empty indexes in python, how to remove?
I am trying to remove a position from an empty list, as a simple example that demonstrates or is trying to remove.我正在尝试从空列表中删除一个位置,作为演示或试图删除的简单示例。
#Test about fruits
fruits = []
fruits.append('maça')
fruits.append('goiaba')
fruits.append('uva')
fruits.append('pera')
fruits.append('bananna')
fruits[1] = []
print (fruits)
Output : ['maça', [], 'uva', 'pera', 'bananna']
输出:
['maça', [], 'uva', 'pera', 'bananna']
Desired output ['maça', 'uva', 'pera', 'bananna']
期望的输出
['maça', 'uva', 'pera', 'bananna']
Just remembering that it is a simple example, so I can apply it in a more robust program that I am developing that presents the same problem of having a "position" in the list with a 'null' or empty value in this case.请记住,这是一个简单的示例,因此我可以将它应用到我正在开发的更健壮的程序中,该程序在这种情况下存在相同的问题,即在列表中具有“空”或空值的“位置”。
Use pop()
to remove an element from a list by its index, rather than assigning an empty value to the index.使用
pop()
通过索引从列表中删除元素,而不是为索引分配一个空值。
fruits.pop(1)
or del
或
del
del fruits[1]
pop()
allows you to retrieve the value being removed at the same time. pop()
允许您检索同时删除的值。
You can use您可以使用
del fruits[1]
水果[1]
See Difference between del, remove and pop on lists for the differences.有关差异,请参阅列表上的 del、remove 和 pop 之间的差异。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.