MYYA
numpy是你的朋友。使用它并跳过 for 循环# sample seriess = pd.Series([list('abcd'), list('efgh'), list('ijkl')])# concat your seriesl = np.concatenate(s)array(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'], dtype='<U1')
犯罪嫌疑人X
它所做的只是展平列表列表,例如nested_list = [[1, 2, 3], [4], [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: for string in row: result.append(string)基本上它作为嵌套循环从左到右读取,但内部代码位于开头。您可以通过弄乱原始代码中的间距来看到这一点:result = [ string for row in series # : <- pretend colons for string in row # : # result.append(string) <- this bit just goes to the start in list comprehension land]顺便说一下,你显然可以更快地使用itertools.chain(但我不确定这是否仍然适用于 a pd.Series):import itertoolsresult = list(itertools.chain(*series.tolist()))