Skip to main content
 首页 » 编程设计

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

2025年05月04日30jyk

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

实际数据:

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]