【问题标题】:How do I make it stop storing everything in the first element of the list?如何让它停止将所有内容存储在列表的第一个元素中?
【发布时间】:2022-12-04 05:08:53
【问题描述】:

我试图将每一行存储在列表的不同元素中。文本文件如下...

244
Large Cake Pan
7
19.99
576
Assorted Sprinkles
3
12.89
212
Deluxe Icing Set
6
37.97
827
Yellow Cake Mix
3
1.99
194
Cupcake Display Board
2
27.99
285
Bakery Boxes
7
8.59
736
Mixer
5
136.94

我试图让 244、576 等在 ID 中。以及名称中的“大蛋糕盘”、“什锦糖屑”等。你明白了,但是它把所有的东西都存储在 ID 中,我不知道如何让它把信息存储在它对应的元素中。

到目前为止,这是我的代码:

import Inventory

def process_inventory(filename, inventory_dict):
    inventory_dict = {}
    inventory_file = open(filename, "r")
    for line in inventory_file:
        line = line.split('\n')
        ID = line[0]
        Name = line[1]
        Quantity = line[2]
        Price = line[3]
        my_inventory = Inventory.Inventory(ID, Name, Quantity, Price)
        inventory_dict[ID] = my_inventory
    inventory_file.close()
    return inventory_dict

def main():
    inventory1={}
    process_inventory("Inventory.txt", inventory1)

【问题讨论】:

标签: python list file dictionary


【解决方案1】:

在您提供的代码中,您在 process_inventory 函数的第二行用一个空字典覆盖了 inventory_dict 参数。这意味着您作为参数传递给函数的字典不会在函数中使用或更新。

要解决此问题,您应该删除行 inventory_dict = {},而是直接使用 inventory_dict 参数。这将确保该函数更新作为参数传递给它的字典。

此外,您在 ' ' 字符,数据中不存在。相反,您应该在空格字符 ' ' 上拆分该行,以便您可以分隔 ID、名称、数量和价格值。

以下是修改 process_inventory 函数以解决这些问题的方法:

def process_inventory(filename, inventory_dict):
    inventory_file = open(filename, "r")
    for line in inventory_file:
        # Split the line on spaces to get the ID, name, quantity, and price values
        values = line.split(' ')
        ID = values[0]
        Name = values[1]
        Quantity = values[2]
        Price = values[3]
        my_inventory = Inventory.Inventory(ID, Name, Quantity, Price)
        inventory_dict[ID] = my_inventory
    inventory_file.close()
    return inventory_dict

通过这些更改,每一行都将被处理并添加到 inventory_dict 字典中,其中 ID 作为键,Inventory 对象作为值。

注意:您提供的代码中没有定义 Inventory 类,因此不清楚应该如何创建 Inventory 对象。您可能需要根据 Inventory 类的定义方式调整这部分代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-02
    • 2022-11-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多