Home > Net >  Python list comprehension with function and loop
Python list comprehension with function and loop

Time:02-27


in the function `mix(L,n)`, is there a way to replace the two lines `for...` and `L...` with one line using the list comprehension? `L = PS(L)` overwrite the old value and take the new list from `PS(L)`. So, I've check and `L = [PS(L) for i in range (n)]` doesn't work because it will add `PS(L)` every time.
L = [1,2,3,4,5,6]
    
def PS(L):
  m1 = L[:len(L)//2]
  m2 = L[len(L)//2:]
  Lf = [i for i in zip(m1, m2) for i in i]
  return Lf

def mix(L,n):
  for i in range (n):
    L = PS(L)
  return L

print(mix(L,2))

Thranks in advance !
Alex

CodePudding user response:

return [PS(L) for i in range(n)] works if you're trying to append.

But what exactly are you trying to do in mix()? Because your code just replaces L with PS(L) n times and sends back a tuple.

CodePudding user response:

L = [1, 2, 3, 4, 5, 6]


def PS(L):
    m1 = L[:len(L) // 2]
    m2 = L[len(L) // 2:]
    L = [i for i in zip(m1, m2) for i in i]
    return L

def mix(n):
    global L
    L = [PS(L) for i in range(n) if i not in L]
    return L


print(mix(2))
  • Related