मैं आज इस मुद्दे में भाग गया, और मैं एक अलग समाधान के साथ आया। यदि आप मुद्रित होने पर कैसा दिखते हैं, इसके बारे में चिंतित हैं, तो आप stdout फ़ाइल ऑब्जेक्ट को एक कस्टम के साथ प्रतिस्थापित कर सकते हैं, जब लिखते हैं() को कॉल किया जाता है, फ्लोट की तरह दिखने वाली किसी भी चीज की खोज करता है, और उन्हें अपने प्रारूप के साथ बदल देता है उन्हें।
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
यह कोई अच्छी बात है, तो आप सिर्फ एक स्ट्रिंग में संख्या डाल रहे हैं, लेकिन अंत में आप शायद फ़ाइल किसी प्रकार का है कि स्ट्रिंग कहीं लिखना चाहें, और आप के साथ है कि फाइल रैप करने के लिए सक्षम हो सकता है उपरोक्त वस्तु। स्पष्ट रूप से एक प्रदर्शन ओवरहेड का थोड़ा सा है।
उचित चेतावनी: मैंने पाइथन 3 में इसका परीक्षण नहीं किया है, मुझे नहीं पता कि यह काम करेगा या नहीं।
समस्या यह है कि मैंने सूचियों के अंदर तैर लिया है, और जब मैं प्रिंट (सूची) पर उस पर कोई नियंत्रण नहीं है। (यह अन्य वस्तुओं के लिए भी लागू होता है, बीटीडब्ल्यू)। स्रोत कोड को संशोधित करना संभव है क्योंकि मुझे सी पता है, लेकिन यह बिल्कुल ठीक नहीं है कि मैं क्या सोच रहा था। धन्यवाद। – AkiRoss
@AkiRoss: तो फिर आप जो फिक्सिंग करना चाहते हैं वह सूची है, फ्लोट नहीं ... –
@AkiRoss, यदि आप अधिक नियंत्रण चाहते हैं तो बस अलग-अलग आइटम प्रिंट करें। –