如何在python中提取单行理解中的子列表项?

如何在python中提取单行理解中的子列表项?,python,python-3.x,list-comprehension,Python,Python 3.x,List Comprehension,我目前正在学习python中列表理解的概念。然而,当我迭代的列表包含长度相等或不同的子列表时,我会遇到巨大的问题。例如,我想将union\u set()的代码转换为一行理解: def union_set(L): S_union = set() for i in range(len(L)): S_union.update(set(L[i])) return S_union L1 = [1, 2, 3] L2 = [4, 5, 6] L3 = [7,

我目前正在学习python中列表理解的概念。然而,当我迭代的列表包含长度相等或不同的子列表时,我会遇到巨大的问题。例如,我想将
union\u set()
的代码转换为一行理解:

def union_set(L):
    S_union = set()

    for i in range(len(L)):
        S_union.update(set(L[i]))

    return S_union


L1 = [1, 2, 3]
L2 = [4, 5, 6]
L3 = [7, 8, 9]

L = [L1, L2, L3]
print(L)

print(union_set(L))

我很确定这应该是可能的(也许通过“不知何故”解包子列表的内容(?),但我很惊讶我遗漏了一些东西。有人能帮忙吗?

使用*打开包装,并将打开的物品传递到
集合。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

使用列表理解,您可以执行以下操作:

>>> L1 = [1, 2, 3]
>>> L2 = [4, 5, 6]
>>> L3 = [7, 8, 9]
>>> L = [L1, L2, L3]
>>> s=set([x for y in L for x in y])
>>> s
set([1, 2, 3, 4, 5, 6, 7, 8, 9])

y迭代子列表,而x迭代y中的项目。

使用空的
集合和
。union
它:

L1 = [1, 2, 3]
L2 = [4, 5, 6]
L3 = [7, 8, 9]

print set().union(L1, L2, L3)
在代码中用作:

L = [L1, L2, L3]

def union_set(L):
    return set().union(*L)

您可以像这样使用
itertools.chain

>>> L1 = [1, 2, 3]
>>> L2 = [4, 5, 6]
>>> L3 = [7, 8, 9]
>>> L = [L1,L2,L3]

>>> set(itertools.chain(*L))
set([1, 2, 3, 4, 5, 6, 7, 8, 9])

*
解压列表,并从子列表中创建列表。

你好,Jon,谢谢您的回复!这不是我想要的列表理解风格,但它看起来非常干净,可读性很强。我想知道人们会如何准确地使用“*-解包操作符”。这就是为什么!谢谢分享!