Hold an object, using class in python

后端 未结 4 1143
猫巷女王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:22

    Another solution (based on Martijn Pieters code) which avoids recursion is:

    try:
        from itertools import zip_longest
    except ImportError:
        # Python 2
        from itertools import izip_longest as zip_longest
    
    def weave_two(row1, row2):
        return [v for v in sum(zip_longest(row1, row2, fillvalue=None), ()) if v is not None]
    
    def weave_rows(*args):
        if len(args) < 2:
            return None
        current = weave_two(args[0], args[1])
        for i in range(2, len(args)):
            current = weave_two(current, args[i])
        return current
    

    usage:

    >>> weave_rows(l1, l2, l3)
    [5.4, 6.7, 6.5, 6.9, 4.5, 7.8, 8.7]
    

提交回复
热议问题