gpt4 book ai didi

python - 制作动态字典python列表

转载 作者:太空狗 更新时间:2023-10-29 22:25:37 26 4
gpt4 key购买 nike

以下是我的文本文件中的数据集。

2.1,3.5,1.4,0.2,Iris
4.9,3.0,1.4,0.2,Ilia
3.7,3.2,1.3,0.2,Iridium

有一个列表名为:

list_of_keys 

其中包含列表中的以下值

['S_Length','S_Width','P_Length','P_Width','Predicate']

所以,问题是,我想创建一个字典列表来保存我的所有数据(来自文本文件),使用字典的 list_of_keys 作为键如下:

dict = 
{'S_Length': 2.1, 'S_Width':3.5 , 'P_Length': 1.4, 'P_Width': 0.2, 'Predicate': Iris},
{'S_Length': 4.9, 'S_Width':3.0 , 'P_Length': 1.4, 'P_Width': 0.2, 'Predicate': Ilia},
... so on!

我目前的情况:

# store all data from the text files as list
all_examples = file.readlines()

for outer_index in range(len(all_examples)):
for inner_index in range(0, len(list_of_keys)+1):

最佳答案

您可以使用如下生成器函数:

def func():
list_of_keys = ['S_Length','S_Width','P_Length','P_Width','Predicate']
with open('example.txt') as f:
for line in f:
yield dict(zip(list_of_keys,line.strip().split(',')))

print(list(func()))
[{'P_Width': '0.2', 'S_Length': '2.1', 'Predicate': 'Iris', 'S_Width': '3.5', 'P_Length': '1.4'}, {'P_Width': '0.2', 'S_Length': '4.9', 'Predicate': 'Ilia', 'S_Width': '3.0', 'P_Length': '1.4'}, {'P_Width': '0.2', 'S_Length': '3.7', 'Predicate': 'Iridium', 'S_Width': '3.2', 'P_Length': '1.3'}]

您可以逐行读取文件并拆分行,然后使用 zip 创建键值对函数,然后将它们转换为字典。

请注意,由于文件对象是一个迭代器,您可以迭代文件对象并使用 with 语句打开文件,这将在 block 的末尾关闭文件。

作为另一种更 pythonic 的方式,您还可以使用 csv 模块来读取您的文本文件:

import csv
def func():
list_of_keys = ['S_Length','S_Width','P_Length','P_Width','Predicate']
with open('example.txt') as f:
spamreader = csv.reader(f, delimiter=',')
return [dict(zip(list_of_keys,row)) for row in spamreader]

print func()

由于 csv.reader 接受定界符参数并返回在一个迭代器中分隔的整行,因此您无需遍历文件并手动拆分它。

如果您想保留顺序,您可以在这两种情况下使用 collections.OrderedDict:

from collections import OrderedDict
import csv
def func():
list_of_keys = ['S_Length','S_Width','P_Length','P_Width','Predicate']
with open('example.txt') as f:
spamreader = csv.reader(f, delimiter=',')
return [OrderedDict(zip(list_of_keys,row)) for row in spamreader]

print func()
[OrderedDict([('S_Length', '2.1'), ('S_Width', '3.5'), ('P_Length', '1.4'), ('P_Width', '0.2'), ('Predicate', 'Iris')]), OrderedDict([('S_Length', '4.9'), ('S_Width', '3.0'), ('P_Length', '1.4'), ('P_Width', '0.2'), ('Predicate', 'Ilia')]), OrderedDict([('S_Length', '3.7'), ('S_Width', '3.2'), ('P_Length', '1.3'), ('P_Width', '0.2'), ('Predicate', 'Iridium')])]

关于python - 制作动态字典python列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35357582/

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