04-05-1993:1.068
1993 年 4 月 12 日:1.079
1993 年 4 月 19 日:1.079
06-06-1994:1.065
1994 年 6 月 13 日:1.073
1994 年 6 月 20 日:1.079
我有天然氣的日期-年份價格的文本檔案,我想計算一年的平均天然氣價格。所以我試著分開,
with open('c:/Gasprices.txt','r') as f:
fullfile=[x.strip() for x in f.readlines()]
datesprices=[(x.split('-')[0], x.split(':')[1]) for x in fullfile]
print(datesprices)
但我不能得到年份和價格資料,而是這樣的資料。
('04', '1.068'), ('04', '1.079')
請讓我知道我應該知道什么。
另外,如果可以的話,請告訴我如何使用拆分資料來計算每年的平均價格。
uj5u.com熱心網友回復:
我認為沒有必要拆分輸入行,因為它們具有固定的日期格式 - 即它的長度是已知的。因此我們可以切片。
with open('gas.txt') as gas:
td = dict()
for line in gas:
year = line[6:10]
price = float(line[11:])
td.setdefault(year, []).append(price)
for k, v in td.items():
print(f'{k} {sum(v)/len(v):.3f}')
輸出:
1993 1.075
1994 1.072
筆記:
這里沒有檢查空行。假設沒有,并且問題中顯示的樣本格式不正確。
此外,不需要剝離傳入的行,因為float()不受前導/尾隨空格的影響
uj5u.com熱心網友回復:
正如已經提到的,要獲得年份,您應該使用更復雜的拆分。但是您的格式似乎非常一致,您可能會選擇:
datesprices=[(x[6:10], x[11:]) for x in fullfile]
但是如何取平均值呢?您需要在某處存盤特定年份的串列。
from statistics import mean
my_dict = {} # could be defaultdict too
for year, price in datesprices:
if year not in my_dict:
my_dict[year] = []
my_dict[year].append(price)
for year, prices in my_dict.items():
print(year, mean(prices))
uj5u.com熱心網友回復:
試試這個
with open('c:/Gasprices.txt','r') as f:
fullfile=[x.strip() for x in f.readlines()]
datesprices=[(x.split('-')[0],x.split('-')[-1].split(':')[0], x.split(':')[1]) for x in fullfile]
print(datesprices)
輸出
[('04', '1993', '1.068'), ('04', '1993', '1.079'), ('04', '1993', '1.079'), ('06', '1994', '1.065'), ('06', '1994', '1.073'), ('06', '1994', '1.079')]
或者
with open('c:/Gasprices.txt','r') as f:
fullfile=[x.strip() for x in f.readlines()]
datesprices=[(x.split('-')[-1].split(':')[0], x.split(':')[1]) for x in fullfile]
print(datesprices)
輸出
[('1993', '1.068'), ('1993', '1.079'), ('1993', '1.079'), ('1994', '1.065'), ('1994', '1.073'), ('1994', '1.079')]
uj5u.com熱心網友回復:
txt = ['04-05-1993:1.068', '04-12-1993:1.079', '04-19-1993:1.079', '06-06-1994:1.065', '06-13-1994:1.073', '06-20-1994:1.079']
price_per_year = {}
number_of_years = {}
for i in txt:
x = txt.split(':')
Date = x[0]
Price = x[1]
year = date.split('-')[2]
if year ~in price_per_year.keys:
price_per_year.update({year:Price})
number_of_years.update({year:1})
else:
price_per_year[year] = Price
number_of_years[year] = 1
av_price_1993 = price_per_year[1993] / number_of_years[1993]
av_price_1994
= price_per_year[1994] / number_of_years[1994]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/473209.html
下一篇:字典內字典排序
