【问题标题】:Print requested data from .txt file从 .txt 文件打印请求的数据
【发布时间】:2021-03-08 11:56:30
【问题描述】:

我有一个包含以下数据的 txt 文件:

buy apples 20
buy oranges 15
sold bananas 5
sold bananas 5
sold pears 8

我写了一个程序来打印香蕉的总销量,但是我一直收到错误

cannot unpack non-iterable builtin_function_or_method object

我该如何解决这个问题?

with open("update.txt") as openfile:
        for line in openfile:
            action, fruit, quantity = line.split
            if action == 'sold':
                    print(f"{fruit} {quantity}")

输出应该是:

bananas 10
pear    8

【问题讨论】:

  • 你需要line.split(" ")
  • 你好,它工作,但是它打印香蕉 5,香蕉 5,梨 8...而不是香蕉 10,梨 8

标签: python python-3.x file-handling


【解决方案1】:

一方面,您需要将split 作为函数调用,即带括号:

action, fruit, quantity = line.split()

此外,如果您想总结每种水果的值,显然不能在阅读时打印它们。一种方法是例如将每个售出的水果存储在dict 中并汇总数量。然后在最后打印它们:

# initialize empty dictionary
sold_fruit = {}

with open("update.txt") as openfile:
    for line in openfile:
        action, fruit, quantity = line.split()
        if action == 'sold':
            # set value for key '<fruit>' to the sum of the old value (or zero if there is no value yet) plus the current quantity
            sold_fruit[fruit] = sold_fruit.get(fruit,0) + int(quantity)

for frt, qty in sold_fruit.items():
    print(f"{frt} {qty}")

输出:

bananas 10
pears 8

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-01
    • 1970-01-01
    • 2019-07-18
    • 1970-01-01
    相关资源
    最近更新 更多