Mi sono imbattuto in questo problema oggi e ho trovato una soluzione diversa. Se sei preoccupato di come appare una volta stampato, puoi sostituire l'oggetto file stdout con uno personalizzato che, quando viene chiamato write(), cerca qualsiasi cosa che assomiglia a float e li sostituisce con il tuo formato per loro.
class ProcessedFile(object):
def __init__(self, parent, func):
"""Wraps 'parent', which should be a file-like object,
so that calls to our write transforms the passed-in
string with func, and then writes it with the parent."""
self.parent = parent
self.func = func
def write(self, str):
"""Applies self.func to the passed in string and calls
the parent to write the result."""
return self.parent.write(self.func(str))
def writelines(self, text):
"""Just calls the write() method multiple times."""
for s in sequence_of_strings:
self.write(s)
def __getattr__(self, key):
"""Default to the parent for any other methods."""
return getattr(self.parent, key)
if __name__ == "__main__":
import re
import sys
#Define a function that recognises float-like strings, converts them
#to floats, and then replaces them with 1.2e formatted strings.
pattern = re.compile(r"\b\d+\.\d*\b")
def reformat_float(input):
return re.subn(pattern, lambda match: ("{:1.2e}".format(float(match.group()))), input)[0]
#Use this function with the above class to transform sys.stdout.
#You could write a context manager for this.
sys.stdout = ProcessedFile(sys.stdout, reformat_float)
print -1.23456
# -1.23e+00
print [1.23456] * 6
# [1.23e+00, 1.23e+00, 1.23e+00, 1.23e+00, 1.23e+00, 1.23e+00]
print "The speed of light is 299792458.0 m/s."
# The speed of light is 3.00e+08 m/s.
sys.stdout = sys.stdout.parent
print "Back to our normal formatting: 1.23456"
# Back to our normal formatting: 1.23456
Non va bene se si sta solo mettendo i numeri in una stringa, ma alla fine probabilmente si vorrà scrivere la stringa a una sorta di file da qualche parte, e si può essere in grado di avvolgere il file con il sopra l'oggetto. Ovviamente c'è un po 'di overhead delle prestazioni.
Fair warning: non ho provato questo in Python 3, non ho idea se avrebbe funzionato.
Il problema è che ho fluttuato all'interno degli elenchi, e quando stampo (elenco) non ne ho il controllo. (Questo vale anche per altri oggetti, btw). Modificare il codice sorgente è fattibile come so C, ma non è esattamente quello che stavo pensando. Grazie. – AkiRoss
@AkiRoss: Quindi ciò che si desidera correggere è l'elenco, non i float ... –
@AkiRoss, se si desidera un maggiore controllo è sufficiente stampare gli elementi singolarmente. –