【问题标题】:How to make multiple list from one list in python如何从python中的一个列表制作多个列表
【发布时间】:2015-12-31 12:09:47
【问题描述】:

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

实际数据:

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] 

【问题讨论】:

  • 发布你的尝试..
  • 到目前为止你尝试了什么?
  • 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(numbers) print list_number[0] '
  • @TigerhawkT3 1 是一个分隔符,我应该从 1 开始创建新列表。

标签: python python-2.7 list-manipulation


【解决方案1】:

不要将原始numbers 的新引用/副本添加到list,而是在看到1 时开始新的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]

【讨论】:

    【解决方案2】:

    我的建议是 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:] 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-30
      • 2012-07-19
      • 1970-01-01
      • 2019-05-09
      相关资源
      最近更新 更多