1

I want to make the multiple list from one list on condition base.

Actual data:

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]

Expected outcome:

[1, 2, 3,4,5,6,7,8,9]
[1, 11, 12, 13]
[1, 21, 22, 25, 6]
[1, 34 ,5 ,6 ,7,78]

Here is my attempt:

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] 
5
  • 1
    post your attempts.. Commented Dec 31, 2015 at 12:11
  • What did you try so far? Commented Dec 31, 2015 at 12:12
  • 1
    Is 1 a separator, or is there some other logic at work? Commented Dec 31, 2015 at 12:14
  • ' 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] ' Commented Dec 31, 2015 at 12:14
  • @TigerhawkT3 1 is a separator and I am supposed to creates new list when it start from 1. Commented Dec 31, 2015 at 12:16

2 Answers 2

5

Rather than adding new references/copies of the original numbers to the list, either start a new list whenever you see a 1 or add to the latest one otherwise:

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

Result:

>>> 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]
Sign up to request clarification or add additional context in comments.

Comments

0

My suggestion is a 2 stepper, first find the indices of the ones, then print from one to the other and from the last to the end:

 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:] 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.