问题描述
我目前正在学习python中列表推导的概念.但是,当我要遍历的列表包含相同或不同长度的子列表时,我会遇到很大的问题.例如,我想将union_set()
的代码转换为单行理解:
I am currently learning the concept of list comprehensions in python. However, I have huge problems when the list I am iterating over contains sublists of equal or different length. For example, I would like to turn the code for union_set()
into a one-line-comprehension:
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))
我非常确定这是有可能的(也许是通过某种方式"解包子列表的内容(?)),但是我深感我在这里遗漏了一些东西.有人可以帮忙吗?
I am pretty sure this should be possible (maybe by 'somehow' unpacking the sublists' content(?)), but I am affraid that I am missing something here. Can anyone help?
推荐答案
使用列表理解,您可以执行以下操作:
Using list-comprehension, you can do something like that:
>>> 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中的项目.
y is iterating over the sublist, while x iterates over items in y.
这篇关于如何在python的单行理解中提取子列表项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!