繁体   English   中英

如何读取一个txt文件并创建一个字典,每个键都具有python中的值列表?

[英]How to read a txt file and create a dictionary with each key having list of values in python?

我正在阅读一个txt文件,其格式为:

in 0.01 -0.07 0.09 -0.02 0.27
and 0.2 0.3 0.5 0.6
to 0.87 0.98 0.54
from 1.2 5.4 0.2 0.4 

我想创建一个字典,使每个单词都是一个键,其值是数字列表,例如:

{in : [0.017077, -0.073018, 0.094730, -0.026420, 0.272884], and : [0.2, 0.3, 0.5 ,0.6]....}

我怎样才能做到这一点? 目前,我正在做类似的事情:

with open('file.txt','r') as text:
    for line in text:
        key, value = line.split()
        res[key] = int(value)
print res

但这给了我错误: too many values to unpack

line.split()返回值列表,python无法告诉您如何在keyvalue之间分割它们,您需要对此进行明确说明

尝试:

vals = line.split()
key = vals[0]
value = [float(x) for x in vals[1:]]
res[key] = value

问题是

key, value = line.split()

例如

>>> a = "in 0.01 -0.07 0.09 -0.02 0.27"
>>> a.split()
['in', '0.01', '-0.07', '0.09', '-0.02', '0.27']
>>> x, y = a.split()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack

拆分会返回两个以上的值,您正在尝试获取2个变量中的值。

你可以试试

key , value = line.split()[0], line.split[1:]

您犯了两个错误-第一个错误是在两个变量中解压缩两个以上的值,第二个错误是使用int()强制转换来获取float。

最简单的解决方案是使用python 2.x:

res = dict()
with open('file.txt','r') as text:
    for line in text:
        record = line.split()
        key = record[0]
        values = [float(value) for value in record[1:]]
        res[key] = values
print res

请记住,在python 3.x中,您可以直接执行以下操作:

key, *values = line.split()

更简洁的版本使用字典理解:

with open('file.txt','r') as text:
    res = {line.split()[0]: [v for v in map(float, line.split()[1:])] for line in text} 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM