Python: merge nested lists

后端 未结 3 1195
天涯浪人
天涯浪人 2020-12-03 12:57

beginner to python here.

I have 2 nested lists that I want to merge:

list1 = [\'a\',
         (b, c),
         (d, e),
         (f, g, h) ]

list2 =         


        
相关标签:
3条回答
  • 2020-12-03 13:33

    If the order within an inner list/tuple is not important, you can use the mathematical set operations.

    print [tuple(set(a)|set(b)) for a,b in zip(x,y)]

    The set(a)|set(b) converts the iterables a and b to sets and takes the union of the two sets. They are then converted back to tuple as desired in the output format.

    As you are a beginner to python, it is strongly recommended to master list comprehensions. It is way too powerful and concise. In addition to making your code more 'pythonic', list comprehensions can act as a friendlier replacement to 'map' and 'filter' functions.

    0 讨论(0)
  • 2020-12-03 13:44
    from operator import add
    list3 = map(add, list1, list2)
    
    0 讨论(0)
  • 2020-12-03 13:47

    Use the power of the zip function and list comprehensions:

    list1 = [('a', ),
            ('b', 'c'),
            ('d', 'e'),
            ('f', 'g', 'h') ]
    
    list2 = [('p', 'q'),
            ('r', 's'),
            ('t', ),
            ('u', 'v', 'w') ]
    
    print [a + b for a, b in zip(list1, list2)]
    
    0 讨论(0)
提交回复
热议问题