gpt4 book ai didi

python - 从文件创建参数列表的列表

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

您好,我正在尝试从文件创建参数列表

最终结果应该是这样的

param=[[字段],[单位],[高度],[站点]]

问题是信息被分成几行,并且某些参数没有全部信息

#info in the file
[field1]
unit=m/s
height=70.4
site=site1
[field2]
height=20.6
site=site2
[field3]
units=m
...

所以我想以这样的方式填写所有字段,如果没有信息则分配 0 或 ''

示例中的最终结果

param={field1:'m/s',70.4,'site1',field2:'',20.6,site2,field3:'m',0,''}

我知道如何从列表列表创建字典,但不设置默认值(“”表示字符串值,0表示数字值)以防某些值丢失

谢谢

最佳答案

您可以使用默认字典进行分组:

from collections import defaultdict

with open("test.txt") as f:
d = defaultdict(list)
for line in map(str.rstrip, f):
if line.startswith("["):
d["fields"].append(line.strip("[]"))
else:
k,v = line.split("=")
d[k].append(v)

输入::

[field1]
unit=m/s
height=70.4
site=site1
[field2]
height=20.6
site=site2
[field3]
unit=m
height=6.0
site=site3

输出:

defaultdict(<type 'list'>, {'fields': ['field1', 'field2', 'field3'], 
'site': ['site1', 'site2', 'site3'], 'unit': ['m/s', 'm'],
'height': ['70.4', '20.6', '6.0']})

如果您确实想按字段分组,可以在以 [ 开头的行上使用 itertools.groupby 进行分组:

from itertools import groupby

with open("test.txt") as f:
grps, d = groupby(map(str.rstrip,f), key=lambda x: x.startswith("[")), {}
for k,v in grps:
if k:
k, v = next(v).strip("[]"), list(next(grps)[1])
d[k] = v
print(d)

输出:

{'field2': ['height=20.6', 'site=site2'], 
'field3': ['unit=m', 'height=6.0', 'site=site3'],
'field1': ['unit=m/s', 'height=70.4', 'site=site1']}

每个 k 都是以 [ 开头的行,然后我们在石斑鱼对象上调用 next 以获得以 [ 开头的下一行的所有行 或 EOF:

关于python - 从文件创建参数列表的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32944724/

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