如何精简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
相关产品推荐
相关产品推荐

