一旦项目从python中的列表中的列表中删除,我怎么能刷新列表

这是相当复杂的,但我希望能够刷新一个更大的列表一旦项目已从较大的列表中的迷你列表中取出.

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

我使用下面的代码将其分成三个列表

split = [listA[i:(i+3)] for i in range(0, len(listA) - 1, 3)]

print(split)

# [['1','2','3'],['4','5','6'],['6','8','9'],['5','3','7']]

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

如果我从第一个列表中删除了#3,那么现在将拆分

del split[0][-1]
split = [['1','2'],['4','5','6'],['6','8','9'],['5','3','7']]

删除#3后,我希望能够刷新列表,使其看起来像;

split = [[‘1′,’2′,’4’],[‘5′,’6′,’6’],[‘8′,’9′,’5’],[‘3’, ‘7’]]

提前致谢

最佳答案 不知道这个列表有多大,但你需要压扁它并重新计算它:

>>> listA = ['1','2','3','4','5','6','6','8','9','5','3','7']
>>> split = [listA[i:(i+3)] for i in range(0, len(listA) - 1, 3)]
>>> split
[['1', '2', '3'], ['4', '5', '6'], ['6', '8', '9'], ['5', '3', '7']]
>>> del split[0][-1]
>>> split
[['1', '2'], ['4', '5', '6'], ['6', '8', '9'], ['5', '3', '7']]
>>> listA = sum(split, []) # <- flatten split list back to 1 level
>>> listA
['1', '2', '4', '5', '6', '6', '8', '9', '5', '3', '7']
>>> split = [listA[i:(i+3)] for i in range(0, len(listA) - 1, 3)]
>>> split
[['1', '2', '4'], ['5', '6', '6'], ['8', '9', '5'], ['3', '7']]
点赞