Python中如何将两列数据配对拼接为指定格式的列表
问题原因
- 你使用的
itertools.product会生成两个序列的笛卡尔积,也就是所有ID和所有Name的全量组合,例如ID 11会和所有5个名字分别配对,自然会生成大量不符合预期的重复内容,不符合按行一一配对的需求。 - 原有字符串拼接逻辑没有预留空格,会生成
The ID11belongs toDavid这类格式错误的内容。
修正方案
方案1:普通列表场景(data为普通字典,ID和Name是两个等长列表)
直接用Python内置的zip函数按位置一一配对两个列表的元素即可:
op = [] # 替换itertools.product为zip,按行配对ID和Name for id_val, name in zip(data['ID'], data['Name']): # 用f-string格式化字符串,自动处理空格,比加号拼接更简洁 dt = f"The ID {id_val} belongs to {name}" op.append(dt) print(dt) print(op)
方案2:Pandas DataFrame场景(你用pandas读取的表格数据)
直接遍历DataFrame的每一行生成结果即可,代码更简洁:
import pandas as pd # 假设你的表格数据已经读入为data这个DataFrame变量 op = [f"The ID {row['ID']} belongs to {row['Name']}" for _, row in data.iterrows()] print(op)
两种方案运行后都可以得到你需要的预期输出:
['The ID 11 belongs to David', 'The ID 12 belongs to Alex', 'The ID 13 belongs to Alice', 'The ID 14 belongs to Mark', 'The ID 15 belongs to Maria']
内容的提问来源于stack exchange,提问作者disukumo
相关产品推荐
相关产品推荐

