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

时间:2015-12-31 12:09:48

标签: python python-2.7 list-manipulation

我想在条件库的基础上从一个列表中创建多个列表。

实际数据:

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 个答案:

答案 0 :(得分:5)

不是将原始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]

结果:

cd dir && cp test1 test2 && cd -

答案 1 :(得分:0)

我的建议是一个2步进,首先找到那些的索引,然后从一个打印到另一个,从最后到最后:

<html>
   <head>
      <title> You searched for: </title>
   </head>
   <body>
      <script>
         <?php
            echo $_GET['name'];
         ?>
      <script>
   </body>
</html>