Python以合理的形式放置列表

2024-05-16 03:26:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个关于python的问题,因为我是这门语言的新手: 我有一个任务,其中几个名单(购物清单)是要阅读,并最终与价格表评估。不幸的是,我有一个问题,把这个购物清单在一个合理的格式,以便我可以计算每个人的购买价值。在练习中,每个步骤都应该写在函数中(阅读价目表、阅读购物清单……)。你知道吗

购物单(客户名称.txt,大约有50个列表作为文本文件)如下所示:

potato X 8
orange X 7
rice X 13
bread X 13

我的函数当前如下所示:

def readShopping():
    for file in glob.glob('./shoppinglists/**'):
        with open(file,'r') as customerList:
            customerList_contents = customerList.read()

对于计算,我使用了这个pricelist,它也是以json格式从文本文件中获取的:

{"rice": 2.10,
"potato":4.21
"orange":3.31,
"eggs":1.92,
"cheese":8.10,
"chicken":5.22}

问题是:我怎样才能把购物清单的格式合理,以便我可以计算出每个人的内容价格?应计算价格并返回值和客户名称。你知道吗


Tags: 函数名称语言客户格式价格购物glob
2条回答

您可以将customerList(作为字符串)直接传递给计算价格的函数,如下所示。你知道吗

例程将字符串转换为表单的子列表列表(对于您的数据):

[['potato', 'X', '8'], ['orange', 'X', '7'], ['rice', 'X', '13'], ['bread', 'X', '13']]

计算值的函数:

def calc_purchase_value(customerList_contents, price_list):
    " Compute purchase value "

    # convert customerList_contents to a list of list
    purchase_list = [x.split() for x in customerList_contents.split('\n') if x.strip()]

    # Iterate through the purchase_list looking up items in the price list
    # Each sublist will be of the form [item, 'X', cnt]
    return sum([price_list.get(item, 0) * int(cnt) for item, x, cnt in purchase_list])

用法示例

使用customerList\u内容(将从文件中读取不同的字符串)

customerList_contents = """
potato X 8
orange X 7
rice X 13
bread X 13
"""

price_list = {"rice": 2.10,
"potato":4.21,
"orange":3.31,
"eggs":1.92,
"cheese":8.10,
"chicken":5.22}

print(calc_purchase_value(purchase_list, price_list))
#>> 84.15

完整解决方案

import glob
import os
import json

def readShopping():
    " Reads each customer shopping list, returning result as a geneerator "
    for file in glob.glob('./shoppinglists/*.txt'):
        with open(file,'r') as customerList:
            contents = customerList.read()
            # return file path and contents
            yield file, contents

def calc_purchase_value(customerList_contents, price_list):
    " Compute purchase value "

    # convert customerList_contents to a list of list
    purchase_list = [x.split() for x in customerList_contents.split('\n') if x.strip()]

    # Iterate through the purchase_list looking up items in the price list
    # Each sublist will be of the form [item, 'X', cnt]
    return sum([price_list.get(item, 0) * int(cnt) for item, x, cnt in purchase_list])

def get_prices():
    " Reads prices from JSON file "
    with open('./shoppinglists/pricelist.json') as json_file:
        return json.load(json_file)

# - Get prices from JSON file
price_list = get_prices()

for file, contents in readShopping():
    # file - path to customer file
    # contents - contents of customer file

    # Extract customer name from file path
    basename = os.path.basename(file)
    customer_name = os.path.splitext(basename)[0]

    # Total price: based upon shopping list and price list
    total_price = calc_purchase_value(contents, price_list)

    # Show results
    print('Customer {} total is: {:.2f}'.format(customer_name, total_price))

在上面,我在文件夹shoppinglist中有2个文本文件“玛丽.txt“和”詹姆斯.txt“(你得说50或更多)。你知道吗

价目表存储在价格表.json你知道吗

的内容玛丽.txt你知道吗

orange X 3
rice X 2
potato X 3
eggs X 2

的内容詹姆斯.txt你知道吗

potato X 8
orange X 7
rice X 13
bread X 13

输出

Customer james total is: 84.15
Customer mary total is: 30.60
shopping_list = {
  'potato' : 8,
  # etc
}

使用Dict对象来存储它。你知道吗

相关问题 更多 >