I write a program to weave lists of floats together, for example:
l1 = [5.4, 4.5, 8.7]
l2 = [6.5, 7.8]
l3 = [6.7, 6.9]
I want to weave l1 into
Your weave function drops the last element of l2
; you need to use itertools.zip_longest() here:
try:
from itertools import zip_longest
except ImportError:
# Python 2
from itertools import izip_longest as zip_longest
def weave_rows(row1, row2):
return [v for v in sum(zip_longest(row1, row2), ()) if v is not None]
Note that you need to return, not print, your output. The izip_longest()
call adds None
placeholders, which we need to remove again from the sum()
output after zipping.
Now you can simply weave in a 3rd list into the output of the previous two:
weave(weave(l1, l2), l3)
Demo:
>>> weave_rows(l1, l2)
[5.4, 6.5, 4.5, 7.8, 8.7]
>>> weave_rows(weave_rows(l1, l2), l3)
[5.4, 6.7, 6.5, 6.9, 4.5, 7.8, 8.7]