gpt4 book ai didi

python - 如何在python中从一个列表中创建多个列表

转载 作者:太空宇宙 更新时间:2023-11-04 08:51:46 25 4
gpt4 key购买 nike

我想根据条件从一个列表中创建多个列表。

实际数据:

numbers = [1, 2, 3,4,5,6,7,8,9, 1, 11, 12, 13, 1, 21, 22, 25, 6, 1, 34 ,5 ,6 ,7,78]

预期结果:

[1, 2, 3,4,5,6,7,8,9]
[1, 11, 12, 13]
[1, 21, 22, 25, 6]
[1, 34 ,5 ,6 ,7,78]

这是我的尝试:

list_number=[]
numbers = [1, 2, 3,4,5,6,7,8,9, 1, 11, 12, 13, 1, 21, 22, 25, 6, 1, 34 ,5 ,6 ,7,78]
for x in numbers:
if x==1:
list_number.append(numbers)

print list_number[0]

最佳答案

与其将原始 numbers 的新引用/副本添加到 list,不如在看到 时开始一个新的 list >1 否则添加到最新的:

list_number = []
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 11, 12, 13, 1, 21, 22, 25, 6, 1, 34, 5, 6, 7, 78]
for x in numbers:
if x==1:
list_number.append([1])
else:
list_number[-1].append(x)

print list_number

结果:

>>> for x in list_number:
... print x
...
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 11, 12, 13]
[1, 21, 22, 25, 6]
[1, 34, 5, 6, 7, 78]

关于python - 如何在python中从一个列表中创建多个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34546348/

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