Union of multiple sets in python

后端 未结 7 974
逝去的感伤
逝去的感伤 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:15

    The itertools module makes short work of this problem:

    >>> from itertools import chain
    >>> list(set(chain.from_iterable(d)))
    [1, '41', '42', '43', '40', '34', '30', '44']
    

    Another way to do it is to unpack the list into separate arguments for union():

    >>> list(set().union(*d))
    [1, '41', '42', '43', '40', '34', '30', '44']
    

    The latter way eliminates all duplicates and doesn't require that the inputs first be converted to sets. Also, it doesn't require an import.

提交回复
热议问题