Hold an object, using class in python

后端 未结 4 1144
猫巷女王i
猫巷女王i 2021-01-26 13:16

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

4条回答
  •  盖世英雄少女心
    2021-01-26 13:44

    Function you wrote returns None, as no return statement is present. Replace print with return and chain calls. You might also need izip_longest instead of zip for lists of nonequal size:

    With izip_longest:

    from itertools import izip_longest
    def weave(l1, l2):
        return filter(None, sum(izip_longest(l1, l2), ())
    

    demo

    >>> weave(weave(l1, l2), l3)
    (5.4, 6.7, 6.5, 6.9, 4.5, 7.8, 8.7)
    

    Without, zip breaks on shortest argument:

    >>> def weave_shortest(l1, l2):
            return sum(zip(l1, l2), ())
    >>> weave_shortest(l3, weave_shortest(l1, l2))
    (5.4, 6.7, 6.5, 6.9)
    

提交回复
热议问题