Python 删除列表中的子列表而不更改列表中其他子列表的索引

Python Removing a sublist in a list without changing the index of other sublists in the list

比如说:

list = { [1,2,3],[4,5,6],[3,4],[2,7,8,9] }

python 中有没有一种方法可以删除子列表并确保其他子列表的索引保持不变。因此,例如,如果我要删除子列表 [3,4],我能否确保 [2,7,8,9] 的索引在这种情况下保持为 3?如果这是可能的,那真的很有帮助!谢谢!

也许吧。这取决于您如何使用列表以及 "listy" 结果对象需要如何。

l = [ [1,2,3],[4,5,6],[3,4],[2,7,8,9] ]

您可以用 None 等其他内容替换子列表。然后你的代码必须知道在处理列表时忽略 None。

print(l[3])
l[2] = None
print(l[3])

或者您可以将列表转换为字典并删除成员。您仍然可以索引该对象,但由于它现在是字典,您的代码将不得不像对待字典一样对待它。

l = dict(enumerate(l))
print l[3]
del l[2]
print l[3]

这些技巧只适用于某些特殊环境。

但是您可以将具有值的索引存储为元组。首先制作一个包含索引和值的修改列表。然后你可以随意删除任何元素。

lst = [[1,2,3],[4,5,6],[3,4],[2,7,8,9]]
modified = list(enumerate(lst))

稍微解释一下:

modified=[]

for i,v in enumerate(lst):
    modified.append((i,v))

print modified

输出:

[(0, [1, 2, 3]), (1, [4, 5, 6]), (2, [3, 4]), (3, [2, 7, 8, 9])]

您可以只删除[3,4]中的元素并保留空的子列表。

>>> lst = [[1,2,3],[4,5,6],[3,4],[2,7,8,9]]
>>> del lst[2][:]
>>> lst
[[1, 2, 3], [4, 5, 6], [], [2, 7, 8, 9]]

请注意,您不应使用 list 作为 variable 名称,因为 listbuilt in function