function - Python weave lists -


i want "weave" 2 numberrows together.

example:

x = [1,2,3] y = [4,5,6]  result = [1,4,2,5,3,6] 

this function, can't find out why doesn't work:

def weave(list1,list2):     lijst = []     = 0     <= len(list1):         lijst += [list1[i]]          lijst += [list2[i]]          + 1 

python's for-loops aren't other languages can have conditional. need use while loop instead or alter for-loop:

def weave(list1,list2):     lijst = []     = 0     while < len(list1):         lijst.append(list1[i])         lijst.append(list2[i])          += 1     return lijst 

i've altered code in variety of ways:

  • use while loop if have condition want loop through
  • you want conditional less length, not less or equal to. because indexing starts @ 0, , if <=, try list1[3] won't exist.
  • use list.append add items list
  • you forgot = in i += 1
  • finally, don't forget return list!

you use zip():

>>> [a b in zip(x, y) in b] [1, 4, 2, 5, 3, 6] 

Comments

Popular posts from this blog

matlab - "Contour not rendered for non-finite ZData" -

delphi - Indy UDP Read Contents of Adata -

qt - How to embed QML toolbar and menubar into QMainWindow -