Home > Blockchain >  complex list comprehension syntax
complex list comprehension syntax

Time:03-14

Just to know if it is possible to write this in a line comprehension and if it is, how to write it.

lst1 = [0,1,2,3,4,5,6,7,8,9,10]
lst2 = [[0,4],[1,5],[2,6],[3,7]]
list3 = []
list4 = []
list5 = []

for l in lst1:
    for k in lst2:
         if l == k[0]:
           list3.append(k)
         elif l==k[1]:
            list4.append(k)
         else:
            list5.append(l)
                 
print('lst1',lst1)
print('lst2',lst2)
print('list3',list3)
print('list4',list4)
print('list5',list5)

CodePudding user response:

You can generally turn a nested for loop that builds a list into a list comprehension by using the same exact for ... in statements in the same order:

list3 = [k for l in lst1 for k in lst2 if l == k[0]]
list4 = [k for l in lst1 for k in lst2 if l == k[1]]
list5 = [l for l in lst1 for k in lst2 if l not in k]

CodePudding user response:

Here you go:

[[list3.append(k) if l == k[0] else (list4.append(k) if l==k[1] else list5.append(l)) for k in lst2] for l in lst1]
  • Related