Python 向后枚举列表的大小,但保持列表向前
所以我有一些代码如下:Python 向后枚举列表的大小,但保持列表向前,python,list,readability,enumerate,Python,List,Readability,Enumerate,所以我有一些代码如下: 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
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
它所做的是,它需要一个列表的长度,它向后迭代,直到它达到0,并且我正在使用的api中的插曲名称和编号也正在打印
所以我想知道的是,是否有一种更具可读性的方法。类似于使用enumerate,它可以向后显示列表的大小,但可以向前显示列表的内容(如果有意义的话)一种简单的方法是只打印
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']))
输出:
[2] Episode 1: show_1
[1] Episode 2: show_2
您可以在enumerate中对i,x执行
(来自用户秀的剧集)
,然后格式化(剧集数量-i…)
。