Gabriel costa
Gabriel costa

Reputation: 161

How get a certain values from a list analyzing the value before in python?

I have a list with integer numbers and I want to extract certain elements with base, in the number before and to increase position to the next number. I would like to do this in loop.

But the numbers in the list will change all the time.

this is my list

data = [3, 119, 119, 119, 10, 103, 111, 111, 103, 108, 101, 97, 112, 
105, 115, 3, 99, 111, 109, 0]

So, I have the first number 3, then I want to extract the next three numbers, 119 119 119, after these three numbers I have number 10, based in the number 10, I want to extract the next ten positions on the list, 103, 111, 111, 103, 108, 101, 97, 112, 105, 115, afeter that I have number 3, and based on that number extract the next three positions 99, 111, 109, when I find the last number 0 the program stops.

this is my attempts

while True:

index1 = 0
index2 = 1

value = data[index1:index2]



index1 = value[0]
index2 = value[0] + 1

print(value)
if value == 0:
    break

Upvotes: 0

Views: 1767

Answers (2)

iz_
iz_

Reputation: 16573

You can try using itertools.islice:

from itertools import islice

data = [3, 119, 119, 119, 10, 103, 111, 111, 103, 108, 101, 97, 112, 105, 115, 3, 99, 111, 109, 0]

data_iter = iter(data)
for i in data_iter:
    if i == 0:
        break
    print(list(islice(data_iter, i)))

Output:

[119, 119, 119]
[103, 111, 111, 103, 108, 101, 97, 112, 105, 115]
[99, 111, 109]

If you want it as a list, just make the below modifications:

from itertools import islice

data = [3, 119, 119, 119, 10, 103, 111, 111, 103, 108, 101, 97, 112, 105, 115, 3, 99, 111, 109, 0]

result = []

data_iter = iter(data)
for i in data_iter:
    if i == 0:
        break
    result.append(list(islice(data_iter, i)))

You can even make it a list comprehension if you want:

data_iter = iter(data)
result = [list(islice(data_iter, i)) for i in data_iter if i != 0]

Upvotes: 2

Patrick Artner
Patrick Artner

Reputation: 51623

You can walk over your data

  • get first element
  • get a list sliced based on current items index and its value
  • skip all those elements you just sliced out repeat until done:

data = [3, 119, 119, 119, 10, 103, 111, 111, 103, 108, 101, 97, 112, 105, 115, 
        3, 99, 111, 109, 0]

part = []
skip = 0
for idx,val in enumerate(data):
    if skip == 0:
        part.append(data[idx+1:idx+1+val])
        skip = val
    else:
        skip -= 1

if not part[-1]:
    part.pop()

print(part)

Output:

[[119, 119, 119], 
 [103, 111, 111, 103, 108, 101, 97, 112, 105, 115], 
 [99, 111, 109]]

Doku:

Upvotes: 2

Related Questions