共計 643 個字符,預計需要花費 2 分鐘才能閱讀完成。
你可以使用 Python 中的文件操作來將數(shù)據(jù)按年份寫入文件。以下是一個示例代碼:
data = [{"year": 2020, "value": 100},
{"year": 2021, "value": 200},
{"year": 2020, "value": 150},
{"year": 2022, "value": 300}
]
# 按年份將數(shù)據(jù)分組
data_by_year = {}
for item in data:
year = item['year']
value = item['value']
if year in data_by_year:
data_by_year[year].append(value)
else:
data_by_year[year] = [value]
# 按年份寫入文件
for year, values in data_by_year.items():
filename = f"data_{year}.txt"
with open(filename, 'w') as file:
for value in values:
file.write(str(value) + '\n')
運行上述代碼后,將會生成三個文件:data_2020.txt、data_2021.txt 和 data_2022.txt。每個文件中的數(shù)據(jù)分別按年份寫入,例如 data_2020.txt 文件中的數(shù)據(jù)為:
100
150
你可以根據(jù)你的具體需求來修改代碼,例如數(shù)據(jù)的格式、文件名等。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完