简体   繁体   English

向后枚举列表的大小,但保持列表向前

[英]Enumerate the size of a list backwards, but keep the list going forwards

So I have some code as follows: 所以我有一些代码如下:

amount_of_episodes = len(episodes_from_user_show)
for x in episodes_from_user_show:
    print("[{0}] Episode {1}: {2}".format(amount_of_episodes, x.episode_number,
                                          x.name))  # Prints the available list of episodes.
    amount_of_episodes -= 1

What it has done is that it takes the length of a list, it iterates backwards until it reaches 0 and the episode name and number from the api I am using is also being printed. 它所做的是,它占用列表的长度,向后迭代,直到达到0,并且还打印了我正在使用的api中的情节名称和编号。

So what I wanted to know is if there was a more readable way of doing this. 因此,我想知道的是,是否存在一种更具可读性的方法。 Something like using enumerate that can display the size of the list going backwards but the content of the list going forwards (if that makes sense)? 诸如使用枚举之类的东西可以显示列表的大小,但是列表的内容向前(如果有意义)?

A simple way to do this is to just print len(values) - index : 一种简单的方法是只打印len(values) - index

shows = [{'id': 1, 'name': 'show_1'},{'id': 2, 'name': 'show_2'}]
for idx, show in enumerate(shows):
    print("[{}] Episode {}: {}".format(len(shows) - idx, show['id'], show['name']))

output: 输出:

[2] Episode 1: show_1
[1] Episode 2: show_2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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