如何从 python 中的一个列表创建多个列表
How to make multiple list from one list in python
我想根据条件从一个列表中创建多个列表。
实际数据:
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
的新 references/copies 添加到 list
,不如在看到 1
时开始新的 list
或添加否则到最新的:
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]
我的建议是一个 2 步进器,首先找到一个的索引,然后从一个到另一个打印,从最后一个打印到最后:
ones_index=[]
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 i,x in enumerate(numbers):
if x==1:
ones_index.append(i)
for i1,i in enumerate(ones_index):
try:
print numbers[i:ones_index[i1+1]]
except:
print numbers[i:]
我想根据条件从一个列表中创建多个列表。
实际数据:
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
的新 references/copies 添加到 list
,不如在看到 1
时开始新的 list
或添加否则到最新的:
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]
我的建议是一个 2 步进器,首先找到一个的索引,然后从一个到另一个打印,从最后一个打印到最后:
ones_index=[]
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 i,x in enumerate(numbers):
if x==1:
ones_index.append(i)
for i1,i in enumerate(ones_index):
try:
print numbers[i:ones_index[i1+1]]
except:
print numbers[i:]