首页 > 解决方案 > 如何操作日期和价格在同一列表项中的列表中的数据?

问题描述

我对这个家庭作业很迷茫,希望有人能指出我正确的方向。我有一份日期清单和该日期每加仑汽油的价格。下面显示了一个示例列表,但文件中的日期是从 1993 年到 2013 年。

此时,我可以读取该文件,但我不知道如何处理列表中的数据。到目前为止,我只处理了列表中的一条数据。

file = open('GasPrices.txt','r')

file_contents = file.read()
get_words = file_contents.split()
print(get_words)

目标是获得每年的平均价格、每月的平均价格、每年的最高和最低价格(显示日期和金额)、从最高到最低的价格列表以及从最低到最高的价格列表。

I don't think I'll have an issue mathing those items, but I'm really struggling to understand how I can "break apart" the date from the price and then after doing the math for the items mentioned above, printing the dollar amount with the date.

Any suggestions?

标签: pythonpython-3.xlist

解决方案


遍历每个项目的列表,并使用date, price = item.split(':'). 这将允许您按“:”进行拆分,并将每个部分分配给不同的变量。

split(':')正在创建一个列表,其中包含由分号分隔的所有字符串片段。

我会做这样的事情:

with open('GasPrice.txt', 'r') as f:
    lines = f.read().splitlines()
data = [line.split(':') for line in lines]

文件中的文本由每一行分割,然后通过分号分割每一行来创建数据列表。


推荐阅读