![](/img/trans.png)
[英]Read floats and strings from a file into a list of tuples with data types intact
[英]Read from file to dictionary as floats instead of strings
我正在從python加載和提取數據,我希望將其存儲在字典中。
我正在使用csv寫入讀取數據,並在外部將其存儲為以逗號分隔的列。 這很好用,但是在最初讀取數據時(顯然)將其讀取為字符串。 我可以使用兩行代碼將它轉換為具有浮點數的鍵和值的字典,但是我的問題是我是否可以將浮點數直接加載到字典中。
我的原始代碼是:
reader = csv.reader(open('testdict.csv','rb'))
dict_read = dict((x,y) for (x,y) in reader)
我已更改為:
reader = csv.reader(open('testdict.csv','rb'))
read = [(float(x),float(y)) for (x,y) in reader]
dict_read = dict(read)
以所需的方式加載數據。
那么,是否有可能修改第一個dict_read = dict((x,y) for (x,y) in reader)
以執行以下代碼呢?
解決方案:解決方案是使用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.