繁花不似锦
您可以这样做:store_x = []for x in b: row = [] for i, xx in enumerate(x): if xx in ba: row.append(i) store_x.append(row)print(store_x)dic2 = []for i, x in enumerate(store_x): row = [] if x: for ex in x: row.append(a[i][ex]) dic2.append(row)print(dic2)输出[[0, 1], [], [], [2]][['text', 'man'], [], [], ['only']]输出可以读取为store_x索引 0 中的值[0,1]和索引 3 中的值[2]。您的代码中的问题是这store_x是一个列表,您需要一个列表列表(2D列表)。一种选择是在第一个循环中使用字典:store_x = {}for ex, x in enumerate(b): row = [] for i, xx in enumerate(x): if xx in ba: row.append(i) if row: store_x[ex] = rowprint(store_x)dic2 = []for i, x in store_x.items(): row = [] if x: for ex in x: row.append(a[i][ex]) if row: dic2.append(row)print(dic2)输出{0: [0, 1], 3: [2]}[['text', 'man'], ['only']]这更像是预期的输出。UPDATE 如注释中所指定,输出最遵循ba的顺序,假设ba缺少的值必须排在最后。代码必须更新为:store_x = {}for ex, x in enumerate(b): row = [] for i, xx in enumerate(x): if xx in ba: row.append(i) if row: store_x[ex] = rowprint(store_x)order = {e: ii for ii, e in enumerate(ba)}dic2 = []for i, x in store_x.items(): row = [] if x: for ex in x: row.append(a[i][ex]) if row: row.sort(key=lambda e: order.get(e, len(ba))) dic2.append(row)print(dic2)输出(测试用例 1){0: [0, 1], 3: [2]}[['text', 'man'], ['only']]输出(测试用例 2){0: [0], 2: [1], 3: [1, 2]}[['text'], ['take'], ['purpose', 'learning']]更新2store_x = {}for ex, x in enumerate(b): row = [] for i, xx in enumerate(x): if xx in ba: row.append(i) if row: row.sort(key=lambda e: ba.index(x[e])) store_x[ex] = rowprint(store_x)order = {e: ii for ii, e in enumerate(ba)}dic2 = []for i, x in store_x.items(): if x: for ex in x: dic2.append(a[i][ex])dic2.sort(key=lambda e: order.get(e, len(ba)))print(dic2)输出(测试用例 1){0: [0, 1], 3: [2]}['text', 'man', 'only']输出(测试用例 2){0: [0], 2: [1], 3: [2, 1]}['text', 'take', 'purpose', 'learning']输出(测试用例3){0: [1, 0], 1: [0], 2: [1, 0], 3: [2, 1]}['funny', 'text', 'take', 'I', 'purpose', 'learning', 'cruel']