普通演讲中的双列表理解

我在我的代码中实现了以下列表理解,并且它有效:

[string for row in series for string in row]

背景:我有一个 pandas 系列的字符串列表。所以系列的每一行都有一个列表,每个列表都有几个字符串。所以我想使用列表理解从系列中的每个列表中提取所有字符串并将它们编译成一个大列表。

问题:仅阅读语法,我很难直观地理解理解中发生的事情。谁能用通俗易懂的英语拼写出来?例如,对于标准列表综合([x for x in z]),我可以将其描述为“一个列表,其中 ax 表示 z 中的每个 x”。

我不知道这是否真的是一个可行的问题,但我认为这值得一问!谢谢。


慕妹3242003
浏览 81回答 2
2回答

MYYA

numpy是你的朋友。使用它并跳过 for 循环# sample seriess = pd.Series([list('abcd'),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;list('efgh'),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;list('ijkl')])# concat your seriesl = np.concatenate(s)array(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'],&nbsp; &nbsp; &nbsp; dtype='<U1')

犯罪嫌疑人X

它所做的只是展平列表列表,例如nested_list = [[1, 2, 3],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;[4],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;[5, 6]]flat_list = [item for inner_list in nested_list for item in inner_list]# flat_list will be [1, 2, 3, 4, 5, 6]要理解它,只需将其写成嵌套的 for 循环即可:result = []for row in series:&nbsp; &nbsp; for string in row:&nbsp; &nbsp; &nbsp; &nbsp; result.append(string)基本上它作为嵌套循环从左到右读取,但内部代码位于开头。您可以通过弄乱原始代码中的间距来看到这一点:result = [&nbsp; &nbsp; string&nbsp;&nbsp; &nbsp; for row in series # : <- pretend colons&nbsp; &nbsp; &nbsp; &nbsp; for string in row # :&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # result.append(string) <- this bit just goes to the start in list comprehension land]顺便说一下,你显然可以更快地使用itertools.chain(但我不确定这是否仍然适用于 a pd.Series):import itertoolsresult&nbsp; = list(itertools.chain(*series.tolist()))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python