You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何改进Python列表推导式:无对应元素时插入默认值?

解决列表长度不一致生成DataFrame的问题

方法一:从统一数据源生成(推荐)

如果你的原始数据是包含不同字段的字典集合,直接遍历每个元素提取对应字段值,缺失时用空字符串填充,这样生成的三个列表天然长度一致:

import pandas as pd

# 示例原始数据(根据实际情况替换)
data = [
    {'Name': 'John', 'Age': '32'},
    {'Name': 'Eric', 'Fruit': 'Apple'},
    {'Name': 'Dave', 'Age': '25', 'Fruit': 'Banana'},
    {'Name': 'Mike', 'Age': '31', 'Fruit': 'Pear'},
    {'Name': 'Charlotte'}
]

# 列表推导式生成,缺失值用空字符串填充
Name = [item.get('Name', '') for item in data]
Age = [item.get('Age', '') for item in data]
Fruit = [item.get('Fruit', '') for item in data]

# 合并为DataFrame
df = pd.DataFrame({'Name': Name, 'Age': Age, 'Fruit': Fruit})
print(df)

输出结果:

Name Age   Fruit
0       John  32        
1       Eric      Apple
2       Dave  25  Banana
3       Mike  31    Pear
4  Charlotte            

方法二:补全已有长度不一的列表

如果已经分别生成了长度不同的列表,先获取三个列表的最大长度,再给短列表补充空字符串,确保长度一致:

import pandas as pd

# 假设已有长度不一致的列表(根据实际情况替换)
Name = ['John', 'Eric', 'Dave', 'Mike', 'Charlotte']
Age = ['32', '25', '31']
Fruit = ['Apple', 'Banana', 'Pear']

# 计算最大长度
max_length = max(len(Name), len(Age), len(Fruit))

# 补全短列表
Name += [''] * (max_length - len(Name))
Age += [''] * (max_length - len(Age))
Fruit += [''] * (max_length - len(Fruit))

# 生成DataFrame
df = pd.DataFrame({'Name': Name, 'Age': Age, 'Fruit': Fruit})
print(df)

这两种方法都能让三个列表长度一致,顺利生成符合需求的DataFrame。

内容的提问来源于stack exchange,提问作者Curious Student

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 13:52:39