gpt4 book ai didi

python - 将文本文件转换为字典列表

转载 作者:行者123 更新时间:2023-12-05 01:50:31 25 4
gpt4 key购买 nike

我有一个这种格式的文本文件 (in_file.txt):

banana 4500 9 
banana 350 0
banana 550 8
orange 13000 6

enter image description here

如何将其转换为 Python 中的字典列表?

代码:

in_filepath = 'in_file.txt'

def data_dict(in_filepath):
with open(in_filepath, 'r') as file:
for line in file.readlines():
title, price, count = line.split()

d = {}
d['title'] = title
d['price'] = int(price)
d['count'] = int(count)

return [d]

终端显示如下结果:

{'title': 'orange', 'price': 13000, 'count': 6}

正确的输出:

{'title': 'banana', 'price': 4500, 'count': 9}, {'title': 'banana', 'price': 350, 'count': 0} , ....

谁能帮我解决我的问题?谢谢!

最佳答案

titles = ["title","price","count"]
[dict(zip(titles, [int(word) if word.isdigit() else word for word in line.strip().split()])) for line in open("in_file.txt").readlines()]

或:

titles = ["title","price","count"]
[dict(zip(titles, [(data:=line.strip().split())[0], *map(int, data[1:])])) for line in open("in_file.txt").readlines()]

你的方法(更正):

in_filepath = 'in_file.txt'

def data_dict(in_filepath):
res = []
with open(in_filepath, 'r') as file:
for line in file.readlines():
title, price, count = line.split()

d = {}
d['title'] = title
d['price'] = int(price)
d['count'] = int(count)
res.append(d)

return res

data_dict(in_filepath)

为什么?因为

  1. ->
    d = {}
d['title'] = title
d['price'] = int(price)
d['count'] = int(count)

for 循环之外,只运行一次,当 ‍‍for 完成时,你只有一个元素

  1. 你返回了你的最后一个元素并且没有使用其他元素并且使用必须创建一个列表并将每个元素附加到 for 循环的最后一行(保存)最后返回结果

@Rockbar 方法:

import pandas as pd

list(pd.read_csv("in_file.txt", sep=" ", header=None, names=["title","price","count"]).T.to_dict().values())

关于python - 将文本文件转换为字典列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73012167/

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