Union of multiple sets in python

后端 未结 7 938
逝去的感伤
逝去的感伤 2020-12-29 02:59
[[1, \'34\', \'44\'], [1, \'40\', \'30\', \'41\'], [1, \'41\', \'40\', \'42\'], [1, \'42\', \'41\', \'43\'], [1, \'43\', \'42\', \'44\'], [1, \'44\', \'34\', \'43\']         


        
相关标签:
7条回答
  • 2020-12-29 03:38

    Tested with python 2 only: I personally like the readability of reduce, paired with a simple conditional function, something like

    somelists = [[1, '41', '40', '42'], [1, '42', '41', '43'], [1, '43', '42', '44'], [1, '44', '34', '43']] # your original lists
    somesets = map(set,somelists) #your lists as sets
    
    def condition(s1,s2): # condition to apply recursively to the sets
        if s1.intersection(s2):
            return s1.union(s2)
    reduce( condition,somesets)
    #{1, '30', '34', '40', '41', '42', '43', '44'}
    

    Of course you can cast this result to a 2d list if you desire list([reduce(...

    I will note that this is something like 3x slower than the chain.fromiterable answer.

    0 讨论(0)
提交回复
热议问题