Home > Software engineering >  how to combine three lists comprehension into one using only one for loop?
how to combine three lists comprehension into one using only one for loop?

Time:09-30

I have a list in range (1 to 31).

The final list is l = [x, y, z]

You can see my code, it is work fine using three for loops:

l = range(1, 31)
x = ([j for (i, j) in enumerate(l) if i % 10 == 0])
y = ([j for (i, j) in enumerate(l) if i % 10 == 4])
z = ([j for (i, j) in enumerate(l) if i % 10 == 9])
l1 = [x, y, z]
print (l1)


l = range(1, 31)
x, y, z = ([j for (i, j) in enumerate(l) if i % 10 == 0]), ([j for (i, j) in enumerate(l) if i % 10 == 4]), ([j for (i, j) in enumerate(l) if i % 10 == 9])
l1 = [x, y, z]
print (l1)

The outputs is:

[[1, 11, 21], [5, 15, 25], [10, 20, 30]]
[[1, 11, 21], [5, 15, 25], [10, 20, 30]]

I tried to do it using only one for loop.

l = ([(x,y,z) for (i1, x), (i2, y), (i3, z) in enumerate(l) if i1 % 10 == 0 and  i2 % 10 == 4 and i3 % 10 == 9])
print l

# l = ([(x,y,z) for ((i, x), (i, y), (i, z)) in enumerate(l) if i % 10 == 0 and  i % 10 == 4 and i % 10 == 9])
# print l

# l = ([(j1,j2,j3) for ((i1,i2,i3), (j1,j2,j3)) in enumerate(l) if i1 % 10 == 0 and  i2 % 10 == 4 and i3 % 10 == 9])
# print l

I got this error:

l = ([(x,y,z) for (i1, x), (i2, y), (i3, z) in enumerate(l) if i1 % 10 == 0 and  i2 % 10 == 4 and i3 % 10 == 9])
ValueError: need more than 2 values to unpack

I don't know if I can do it or not.

please help me.

CodePudding user response:

Try -

l = range(1, 31)
mylist = []
lst = [0, 4, 9]
for i in lst:
    mylist.append([b for a, b in enumerate(l) if a % 10 == i])

print(mylist)

Or list comprehension -

mylist = [[b for a, b in enumerate(l) if a % 10 == i] for i in lst]

CodePudding user response:

Your solution is the best way here, other ways would be to create a for loop:

lst = []
for x in [0, 4, 9]:
    lst.append([j for i, j in enumerate(l) if i % 10 == x])

Output:

>>> lst
[[1, 11, 21], [5, 15, 25], [10, 20, 30]]
>>> 
  • Related