简体   繁体   中英

How to pretty-print a Python list with indices?

How can I pretty-print a (possibly nested) Python list with indices , similar to the Perl's Data::Printer module, eg for L = ['a', 'b', None, 'c'] the output should be something like this:

[
    [0] 'a',
    [1] 'b',
    [2] None,
    [3] 'c',
]

you can use enumerate to get the indices, and use pprint to pretty-print a python list. For example:

pprint.pprint([{num: value} for num, value in enumerate(L)], width=20)

and the output is:

[{0: 'a'},
 {1: 'b'},
 {2: None},
 {3: 'c'}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM