Sujet : Re: Lprint = ( Lisp-style printing ( of lists and strings (etc.) ) in Python )
De : hjp-python (at) *nospam* hjp.at (Peter J. Holzer)
Groupes : comp.lang.pythonDate : 01. Jun 2024, 10:24:14
Autres entêtes
Message-ID : <mailman.79.1717230255.2909.python-list@python.org>
References : 1 2
Pièces jointes : signature.asc (application/pgp-signature) On 2024-05-30 21:47:14 -0700, HenHanna via Python-list wrote:
[('the', 36225), ('and', 17551), ('of', 16759), ('i', 16696), ('a', 15816),
('to', 15722), ('that', 11252), ('in', 10743), ('it', 10687)]
((the 36225) (and 17551) (of 16759) (i 16696) (a 15816) (to 15722) (that
11252) (in 10743) (it 10687))
i think the latter is easier-to-read, so i use this code
(by Peter Norvig)
This doesn't work well if your strings contain spaces:
Lprint(
[
["Just", "three", "words"],
["Just", "three words"],
["Just three", "words"],
["Just three words"],
]
)
prints:
((Just three words) (Just three words) (Just three words) (Just three words))
Output is often a compromise between readability and precision.
def lispstr(exp):
# "Convert a Python object back into a Lisp-readable string."
if isinstance(exp, list):
This won't work for your example, since you have a list of tuples, not a
list of lists and a tuple is not an instance of a list.
return '(' + ' '.join(map(lispstr, exp)) + ')'
else:
return str(exp)
def Lprint(x): print(lispstr(x))
I like to use pprint, but it's lacking support for user-defined types. I
should be able to add a method (maybe __pprint__?) to my classes which
handle proper formatting (with line breaks and indentation).
hp
-- _ | Peter J. Holzer | Story must make more sense than reality.|_|_) | || | | hjp@hjp.at | -- Charles Stross, "Creative writing__/ | http://www.hjp.at/ | challenge!"