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 l2:
[5.4, 6.5, 4.5, 7.8, 8.7]
And now I want it in a class so I can hold this result and weave l3 into it:
[5.4, 6.7, 6.5, 6.9, 4.5, 7.8, 8.7]
The function I wrote two weave two lines together is:
def Weave_number_rows(row1,row2): #enter 2 rows of numbers as lists
l1 = row1
l2 = row2
woven = sum(zip(l1, l2), ())
print woven
How to hold the result with a class and weave the next line into it?
OK, as peoples comments, this seems a strange case to start using classes but something like this should work:
This creates a
Weaver
objectw
and initialises it withl1
. Then you weave the other lists in one by one and it stores the result internally and finally you access and print that result.Another solution (based on Martijn Pieters code) which avoids recursion is:
usage:
Your weave function drops the last element of
l2
; you need to useitertools.zip_longest()
here:Note that you need to return, not print, your output. The
izip_longest()
call addsNone
placeholders, which we need to remove again from thesum()
output after zipping.Now you can simply weave in a 3rd list into the output of the previous two:
Demo:
Function you wrote returns
None
, as no return statement is present. Replaceprint
withreturn
and chain calls. You might also needizip_longest
instead of zip for lists of nonequal size:With izip_longest:
demo
Without, zip breaks on shortest argument: