Python:将文本文件的行转换并连接到具有列表值的字典中

标签 python file dictionary

我有一个文本文件,其中包含任意(非 Python)四行 block 列表,如下所示:

WHAT
EVER
0.00000904
17577

FOO
BAR
7.00000031
426

该文件包含数千个这样的 block 。如何将文件中的数据转换为列表字典,其中键是每个 block 的前两行,连接起来,接下来的两行是列表值?例如:

{'WHATEVER': [0.00000904, 17577], 'FOOBAR': [7.00000031, 426]}

最佳答案

尝试以下操作:

import re

# Open the file
data = open('odd_lines.txt').read()

# Split on the double newline characters
data = data.split("\n\n")

# Split each element of the data list on the newline characters followed by a float
data = [re.split("\n(\d+\.\d+)", x) for x in data]

# Put the data in a dictionary with the key being the first element of each element of the data list.
# Make sure to replace the newline character with an empty space
output = {x[0].replace("\n",""):[float(y) for y in x[1:]] for x in data}

print(output)

这应该产生:

#{'FOOBAR': [7.00000031, 426], 'WHATEVER': [0.00000904, 17577]}

以下是起始文件 (odd_lines.txt):

WHAT
EVER
0.00000904
17577

FOO
BAR
7.00000031
426

我希望这会有所帮助。

关于Python:将文本文件的行转换并连接到具有列表值的字典中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41081425/

相关文章:

c - scanf() 语句上的段错误(核心转储)

Python 字典 : changing the order of nesting

python - pandas:如何将字典转换为转置数据框?

python - 为什么要替换原始图像矩阵值?

用 C 创建一个简单的配置文件和解析器

python - 将计数字段添加到 django rest 框架序列化程序

javascript - JS中访问特定URL进行文件读取

ios - 实例方法 'appendInterpolation(_:formatter:)'要求 'Any'继承自 'NSObject'

python - 不必在 Python 中的类继承中重新定义属性

python - 字典操作顺序