简体   繁体   中英

How can I use list slices in .format()?

So say that I have list a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]. But say that depending on the rest of the program, I can't be sure how long a will be, but I want to display it using .format. How could I reference the last four elements? (without reversing the list and referencing the first four.)

I think this is what you want, use [-4:] to get the last four elements, then unpack them:

>>> a=range(10)
>>> "{} {} {} {}".format(*a[-4:])
'6 7 8 9'

Hope this helps.

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