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

Python读取txt生成价格数量字典出现多余字符键问题求助

问题根源

生成单个字符键的问题来自代码中两段冗余的遍历逻辑:

  • product[0]是商品名字符串,直接遍历字符串会逐个返回单个字符,这两段for循环主动将单个字符作为键添加到了prices和quantities字典中
  • 这两段逻辑属于完全无用的错误代码,还重复覆盖了price、quantity变量的原有定义
修正方案

不改动现有函数结构的前提下,仅删除两段冗余的for循环即可,修正后的完整代码如下:

def read_file(file_name, prices, quantities):
    file = open(file_name, 'r')

    for line in file:
        product = line.strip('\n').split(';')
        # 可选:增加格式校验避免文件行格式错误引发索引报错
        if len(product) < 3:
            continue
        name, price = product[0], product[1]
        prices[name] = price
        name, quantity = product[0], product[2]
        quantities[name] = quantity
        
            
    print(prices)
    print(quantities)
def main():
    #init dictionaries
    prices = {}
    quantities = {}
    #read_file
    read_file("initial_inventory-1.txt", prices, quantities)
main()

(可选优化建议:可以将open替换为with open上下文管理器,自动处理文件关闭,避免资源泄漏)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 17:36:05