Py学习  »  Python

Python-以合理的格式放置列表

ziBBer • 6 年前 • 1905 次点击  

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

购物列表(customerName.txt,大约有50个列表作为textfile)如下所示:

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()

对于计算,我使用这个价格表,它也是从一个json格式的文本文件中得到的:

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

问题是:如何将购物清单以合理的格式放置,以便我可以为每个人计算内容的价格?应计算价格并返回值和客户名称。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/54322
文章 [ 2 ]  |  最新文章 6 年前
ycao
Reply   •   1 楼
ycao    6 年前
shopping_list = {
  'potato' : 8,
  # etc
}

使用 Dict

DarrylG
Reply   •   2 楼
DarrylG    6 年前

您可以将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_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))

在上面,我有两个文本文件在文件夹购物列表“Mary.txt”和“James.txt”(你会说50或更多)。

Mary.txt的内容

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

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

Customer james total is: 84.15
Customer mary total is: 30.60