代码之家  ›  专栏  ›  技术社区  ›  Adnan Ghaffar UBIK LOAD PACK

如何在python中从一个列表生成多个列表

  •  1
  • Adnan Ghaffar UBIK LOAD PACK  · 技术社区  · 9 年前

    我想根据条件从一个列表中生成多个列表。

    实际数据:

    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] 
    
    2 回复  |  直到 9 年前
        1
  •  5
  •   TigerhawkT3    9 年前

    而不是添加原始文件的新参考/副本 numbers 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
  •  0
  •   Ezer K    9 年前

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