python - 如何操作日期和价格在同一列表项中的列表中的数据?
问题描述
我对这个家庭作业很迷茫,希望有人能指出我正确的方向。我有一份日期清单和该日期每加仑汽油的价格。下面显示了一个示例列表,但文件中的日期是从 1993 年到 2013 年。
- 04-05-1993:1.068
- 1993 年 4 月 12 日:1.079
- 1994 年 1 月 3 日:0.992
- 1994 年 1 月 10 日:0.995
- 01-02-1995:1.127
- 01-09-1995:1.134
此时,我可以读取该文件,但我不知道如何处理列表中的数据。到目前为止,我只处理了列表中的一条数据。
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?
解决方案
遍历每个项目的列表,并使用date, price = item.split(':')
. 这将允许您按“:”进行拆分,并将每个部分分配给不同的变量。
split(':')
正在创建一个列表,其中包含由分号分隔的所有字符串片段。
我会做这样的事情:
with open('GasPrice.txt', 'r') as f:
lines = f.read().splitlines()
data = [line.split(':') for line in lines]
文件中的文本由每一行分割,然后通过分号分割每一行来创建数据列表。
推荐阅读
- html - 如何进行 html 图像输入,然后在其上运行 python 算法(对于网站)?
- vue.js - cmd中的vue安装不断向我显示不推荐使用的请求如何修复?
- python - 如何在python中按低于和高于x的值拆分列表
- python - 尝试排序时的无限循环,在 Python 中随机打破关系
- eclipse - Eclipse 快速修复悬停
- php - 从 php 数组中取消设置变量
- image-processing - 给定从图像名称到类标签的映射,如何使用 keras ImageDataGenerator flow_from_directory?
- flutter - 在 AES CTR 模式下,输入数据必须是密码块大小的倍数
- c# - 如何评估 InstanceMethodCallExpressionN
- python - 如何停止在 Python 中裁剪 Tkinter PhotoImage