简体   繁体   English

从文件到字典以浮点数而不是字符串的形式读取

[英]Read from file to dictionary as floats instead of strings

I'm loading and extracting data from python, which I want to be stored in a dictionary. 我正在从python加载和提取数据,我希望将其存储在字典中。

I'm using csv to write read the data and externally it is just stored as to comma-separated columns. 我正在使用csv写入读取数据,并在外部将其存储为以逗号分隔的列。 This works great, but when the data is initially read it (obviously) is read as string. 这很好用,但是在最初读取数据时(显然)将其读取为字符串。 I can convert it to a dictionary with both keys and values as floats using two lines of code, but my question whether I can load the data directly as floats into a dictionary. 我可以使用两行代码将它转换为具有浮点数的键和值的字典,但是我的问题是我是否可以将浮点数直接加载到字典中。

My original code was: 我的原始代码是:

reader = csv.reader(open('testdict.csv','rb'))
dict_read = dict((x,y) for (x,y) in reader)

Which I have changed to: 我已更改为:

reader = csv.reader(open('testdict.csv','rb'))
read = [(float(x),float(y)) for (x,y) in reader]
dict_read = dict(read)

which loads the data in the desired way. 以所需的方式加载数据。

So, is it possible to modify the first dict_read = dict((x,y) for (x,y) in reader) to do what the code below does? 那么,是否有可能修改第一个dict_read = dict((x,y) for (x,y) in reader)以执行以下代码呢?

SOLUTION: The solution is to use the map-function, which has to be used on iterable objects: 解决方案:解决方案是使用map函数,该函数必须在可迭代对象上使用:

dict_read = dict(map(float,x) for x in reader)

尝试这个:

dict_read = dict((map(float,x) for x in reader)

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

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