gpt4 book ai didi

python - 一旦从 python 列表中的列表中删除了一个项目,我如何刷新列表

转载 作者:太空宇宙 更新时间:2023-11-03 13:22:21 25 4
gpt4 key购买 nike

这很复杂,但我希望能够在项目从较大列表中的迷你列表中取出后刷新较大的列表。

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']]

关于python - 一旦从 python 列表中的列表中删除了一个项目,我如何刷新列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9795031/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com