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

Python3如何将用户输入存入字典并用tabulate模块生成表格

实现方案

首先安装依赖:

pip install tabulate

方案1:支持自定义加油站名称+油价

完全支持用户自定义输入加油站名称和对应油价,自带输入合法性校验:

from tabulate import tabulate

# 初始化存储数据的字典
gas_price_dict = {}
# 可按需调整收集的条目数量
collect_count = 5

print(f"请依次输入{collect_count}组加油站数据:")
for i in range(collect_count):
    station = input(f"第{i+1}个加油站名称:").strip()
    # 油价输入校验,避免非数字输入导致程序崩溃
    while True:
        price_str = input(f"{station}的油价:").strip()
        try:
            price = float(price_str)
            break
        except ValueError:
            print("输入非法,请输入数字格式的油价")
    gas_price_dict[station] = price

# 将字典转换为tabulate要求的二维列表格式
table = [["Gas Station Name", "Price"]]
for name, p in gas_price_dict.items():
    table.append([name, f"{p:.2f}"])

# 渲染输出表格
print(tabulate(table, headers='firstrow', tablefmt='grid'))

方案2:沿用固定加油站名称,仅自定义油价

如果不需要修改加油站名称,仅替换原有固定数据里的价格,可以用这个版本:

from tabulate import tabulate

# 固定加油站名称列表,和你原有代码的站点保持一致
stations = ["Shell", "Texaco", "BP", "Sams Club", "Kroger Gas", "Cosco Gas"]
gas_price_dict = {}

print("请依次输入对应加油站的油价:")
for s in stations:
    while True:
        price_str = input(f"{s}的油价:").strip()
        try:
            price = float(price_str)
            break
        except ValueError:
            print("输入非法,请输入数字格式的油价")
    gas_price_dict[s] = price

# 生成表格数据
table = [["Gas Station Name", "Price"]]
for name, p in gas_price_dict.items():
    table.append([name, f"{p:.2f}"])

print(tabulate(table, headers='firstrow', tablefmt='grid'))

核心说明

  • 所有输入数据优先存入字典gas_price_dict,满足需求要求
  • 替换了不安全的eval()方法,增加输入校验避免程序异常崩溃
  • 油价统一保留2位小数输出,格式更规范

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 12:18:04