[英]Read floats and strings from a file into a list of tuples with data types intact
假設我有一個文件example.txt
,它看起來像這樣:
12.592,92.219,Cat
42.643765,72.268234,Dog
12.24312121,22.24312121,Parrot
54.12311,91.32811,Monkey
...
如何將前兩個浮點值和字符串映射到元組列表? 見下文:
[('12.592','92.219','Cat'), ('42.643765','72.268234','Dog'), ('12.24312121','22.24312121','Parrot'), ('54.12311','91.32811','Monkey')]
在我將字符串值引入example.txt
之前,我能夠使用以下方法成功地將文件中的浮點數讀入元組列表中:
with open('data/example.txt') as f:
dataset = [tuple(map(float, i.split(','))) for i in f]
輸出: [('12.592','92.219'), ('42.643765','72.268234'), ('12.24312121','22.24312121'), ('54.12311','91.32811')]
用:
with open('data/example.txt') as f:
# split each line by ","
rows = [i.strip().split(",") for i in f]
# transform only the first two chunks (numbers) and leave the last one as a string
dataset = [(*map(float, numbers), string) for *numbers, string in rows]
print(dataset)
輸出
[(12.592, 92.219, 'Cat'), (42.643765, 72.268234, 'Dog'), (12.24312121, 22.24312121, 'Parrot'), (54.12311, 91.32811, 'Monkey')]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.