è possibile utilizzare una funzione di generatore di come seguire:
def func():
list_of_keys = ['S_Length','S_Width','P_Length','P_Width','Predicate']
with open('example.txt') as f:
for line in f:
yield dict(zip(list_of_keys,line.strip().split(',')))
print(list(func()))
[{'P_Width': '0.2', 'S_Length': '2.1', 'Predicate': 'Iris', 'S_Width': '3.5', 'P_Length': '1.4'}, {'P_Width': '0.2', 'S_Length': '4.9', 'Predicate': 'Ilia', 'S_Width': '3.0', 'P_Length': '1.4'}, {'P_Width': '0.2', 'S_Length': '3.7', 'Predicate': 'Iridium', 'S_Width': '3.2', 'P_Length': '1.3'}]
è possibile leggere il file riga per riga e dividere le linee, quindi creare le coppie di chiavi e valori utilizzando la funzione zip
e quindi convertirli in un dizionario.
Si noti che poiché un oggetto file è un iteratore, è possibile scorrere l'oggetto file e utilizzare l'istruzione with
per aprire il file che chiuderà il file alla fine del blocco.
come un altro modo alternativo e più divinatorio è anche possibile utilizzare il modulo csv
per leggere il file di testo:
import csv
def func():
list_of_keys = ['S_Length','S_Width','P_Length','P_Width','Predicate']
with open('example.txt') as f:
spamreader = csv.reader(f, delimiter=',')
return [dict(zip(list_of_keys,row)) for row in spamreader]
print func()
Iscritto da csv.reader
accetta un argomento delimitatore e restituisce tutta delle vostre linee separate in un unico iteratore si don' t necessario scorrere il file e dividerlo manualmente.
E se si desidera conservare l'ordine è possibile utilizzare collections.OrderedDict
in entrambi i casi:
from collections import OrderedDict
import csv
def func():
list_of_keys = ['S_Length','S_Width','P_Length','P_Width','Predicate']
with open('example.txt') as f:
spamreader = csv.reader(f, delimiter=',')
return [OrderedDict(zip(list_of_keys,row)) for row in spamreader]
print func()
[OrderedDict([('S_Length', '2.1'), ('S_Width', '3.5'), ('P_Length', '1.4'), ('P_Width', '0.2'), ('Predicate', 'Iris')]), OrderedDict([('S_Length', '4.9'), ('S_Width', '3.0'), ('P_Length', '1.4'), ('P_Width', '0.2'), ('Predicate', 'Ilia')]), OrderedDict([('S_Length', '3.7'), ('S_Width', '3.2'), ('P_Length', '1.3'), ('P_Width', '0.2'), ('Predicate', 'Iridium')])]
Per un OP che itera su un file utilizzando 'range (len())' questo richiede _un bit in più_ spiegazione. – bereal
@bereal In effetti, ho appena aggiunto. – Kasramvd