Hold an object, using class in python

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

    OK, as peoples comments, this seems a strange case to start using classes but something like this should work:

    from itertools import zip_longest
    
    class Weaver():
        def __init__(self,data):
            self.result = data
    
        def weave(data):
            self.result = sum(zip_longest(self.result, data),()) # or whatever version
                                                                 # works best from
                                                                 # the other answers
    
    w = Weaver(l1)
    w.weave(l2)
    w.weave(l3)
    print(w.result)
    

    This creates a Weaver object w and initialises it with l1. Then you weave the other lists in one by one and it stores the result internally and finally you access and print that result.

提交回复
热议问题