使用 * 进行拆包并将拆包的物品传递给set.union
:
>>> L = [L1, L2, L3]
>>> set.union(*(set(x) for x in L))
set([1, 2, 3, 4, 5, 6, 7, 8, 9])
使用的高效版本itertools
:
>>> from itertools import islice
>>> set.union(set(L[0]),*islice(L,1,None))
set([1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> from itertools import chain
>>> set(chain.from_iterable(L))
set([1, 2, 3, 4, 5, 6, 7, 8, 9])
时间比较:
>>> L = [L1, L2, L3]*10**5
>>> %timeit set.union(*(set(x) for x in L))
1 loops, best of 3: 416 ms per loop
>>> %timeit set(chain.from_iterable(L)) # winner
1 loops, best of 3: 69.4 ms per loop
>>> %timeit set.union(set(L[0]),*islice(L,1,None))
1 loops, best of 3: 78.6 ms per loop
>>> %timeit set().union(*L)
1 loops, best of 3: 105 ms per loop
>>> %timeit set(chain(*L))
1 loops, best of 3: 79.2 ms per loop
>>> %timeit s=set([x for y in L for x in y])
1 loops, best of 3: 151 ms per loop