How to print out a numbered list in Python 3

故事扮演 提交于 2020-06-25 06:44:13

问题


How do I print out the index location of each of a python list so that it starts at 1, rather than 0. Here's an idea of what I want it to look like:

    blob = ["a", "b", "c", "d", "e", "f"]
    for i in blob:
        print(???)

Output:

1   a
2   b
3   c
4   d
5   e

What I need to know is how do I get those numbers to show up alongside what I'm trying to print out? I can get a-e printed out no problem, but I can't figure out how to number the list.


回答1:


for a, b in enumerate(blob, 1):
    print '{} {}'.format(a, b)



回答2:


You would need to enumerate your list. That means that for every letter, it has a corrosponding number.

Here is an example of your working code:

blob = ["a", "b", "c", "d", "e", "f"]

for number, letter in enumerate(blob):
    print(number, letter)

The enumerate function will give the variable number the position of the variable letter in your list every loop.

To display them, you can just use print(number, letter) to display them side by side.




回答3:


Another solution using built-in operations:

Edit: In case you need extra space:

s1 = ['a', 'b', 'c', 'd']
for i in s1:
    print(s1.index(i) +1, end=' ')
    print(" ",i)

Output:

1   a
2   b
3   c
4   d


来源:https://stackoverflow.com/questions/29811082/how-to-print-out-a-numbered-list-in-python-3

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