Numbered list in python

倖福魔咒の 提交于 2020-01-30 08:05:28

问题


I need to make a numbered list from list elements in python. Example list:

destinations = ['Los Angeles ', 'Rhodos ', 'Dubai ', 'Manila ', 'Mallorca ', 'New York ']

I need to print out elements as numbered list:

1. Los Angeles 
2. Rhodos 
3. Dubai 
4. Manila 
5. Mallorca 
6. New York

If I do:

print ('\n'.join(destinations)) 

It prints out elements on separate lines, but I cannot add numbers.


回答1:


You simply use enumerate() and count from 1

>>> destinations = ['Los Angeles ', 'Rhodos ', 'Dubai ', 'Manila ', 'Mallorca ', 'New York ']  
>>> for index, value in enumerate(destinations, 1):
...     print("{}. {}".format(index, value))
... 
1. Los Angeles 
2. Rhodos 
3. Dubai 
4. Manila 
5. Mallorca 
6. New York 



回答2:


for i, dest in enumerate(destinations, 1):
    print(" %d. %s" % (i, dest))


来源:https://stackoverflow.com/questions/37344371/numbered-list-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!