gpt4 book ai didi

python - 如何在列表中构建字典数据?

转载 作者:太空宇宙 更新时间:2023-11-04 02:40:19 25 4
gpt4 key购买 nike

我有这个程序:

def file(fname):
lines = open(fname).read().splitlines()
return(lines)
print(file('venue.txt'))

结果是这样的,我把它改成了列表:

['room 1,  10,  250']

我如何用它建立字典数据,以便它可以像这样:

[{'name': 'room 1', 'max': 10, 'cost': 250}]

一些线索也许可以帮助我构建它。谢谢

编辑:

def file(fname):
lines = open(fname).read().splitlines()
new = []
for i in lines:
split = i.split(', ')
new.append({'name':split[0],'max':split[1],'cost':split[2]})
return(new)
print(file('venue.txt'))

它打印:

new.append({'name':split[0],'max':split[1],'cost':split[2]})
IndexError: list index out of range

这是什么意思?

最佳答案

你可以试试这个:

import re
def file(fname):
lines = open(fname).read().splitlines()
return(lines)
headers = ["name", "max", "cost"]
data1 = [re.split(",\s+", i) for i in file("venue.txt")]
final_data = [{a:b for a, b in zip(headers, data} for data in data1]
print(final_data)

关于python - 如何在列表中构建字典数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46746281/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com