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

如何精简Python中打印CSV数据的大量print语句?

精简Python打印语句的方法

针对你分散的print语句,有几种高效的精简方式,同时还能提升代码可读性:

1. 使用f-string(Python 3.6+ 优先推荐)

这是最简洁直观的写法,直接在字符串中嵌入变量和表达式,同时把重复计算的结果存为变量避免冗余:

avg = round(get_avg(people))
diff = people[owner]["plugs"] - avg

print(f"\n{people[owner]['first_name']} {people[owner]['last_name']} owns the most buttplugs with a total of {people[owner]['plugs']} buttplugs!")
print(f"That's {diff} more buttplugs than the average of {avg}!\n")

2. 使用str.format()方法

兼容Python 3.6之前的版本,通过占位符填充内容:

avg = round(get_avg(people))
diff = people[owner]["plugs"] - avg

print("\n{} {} owns the most buttplugs with a total of {} buttplugs!".format(
    people[owner]['first_name'],
    people[owner]['last_name'],
    people[owner]['plugs']
))
print("That's {} more buttplugs than the average of {}!\n".format(diff, avg))

3. 字符串拼接(不推荐,可读性差)

将所有内容拼接成完整字符串后一次性打印,注意数值类型需要转成字符串:

avg = round(get_avg(people))
diff = people[owner]["plugs"] - avg

print("\n" + people[owner]['first_name'] + " " + people[owner]['last_name'] + " owns the most buttplugs with a total of " + str(people[owner]['plugs']) + " buttplugs!")
print("That's " + str(diff) + " more buttplugs than the average of " + str(avg) + "!\n")

4. 利用print多参数特性

print支持传入多个参数,默认用空格分隔,适合简单场景:

avg = round(get_avg(people))
diff = people[owner]["plugs"] - avg

print("\n", people[owner]['first_name'], people[owner]['last_name'], "owns the most buttplugs with a total of", people[owner]['plugs'], "buttplugs!")
print("That's", diff, "more buttplugs than the average of", avg, "!\n")

核心优化点:把重复计算的round(get_avg(people))存为变量avg,既减少重复计算开销,也让代码更简洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 14:45:44