Python列表遍历问题:如何按顺序输出列表元素并附带递增序号(从Francisco到Antonio)
Hey there! Let's get your code working properly and make it even cleaner. First, let's break down the two main issues in your current code:
1. Index Out-of-Bounds Error
Python lists use 0-based indexing—meaning the first element is at position 0, not 1. When you use range(1,11), your loop variable x goes from 1 to 10. But your list only has indices from 0 to 9 (since there are 10 elements), so list[10] will throw an IndexError.
2. Syntax Error in Print Statement
You're missing an operator to combine the list element with the rest of the string. You need either a + for string concatenation or a comma to separate print arguments.
Solution 1: Use enumerate() (Most Pythonic Way)
The enumerate() function was made exactly for this scenario—it lets you loop through a list and get both the element and its position (with an optional starting number). Here's how to use it:
names = ['Francisco', 'Marcelle', 'Olivia', 'José', 'Guilherme', 'Maria', 'Arthur', 'Lucas', 'Lurdes', 'Antonio'] # Start numbering from 1 instead of the default 0 for number, name in enumerate(names, start=1): print(f"{name}, your number on the list is {number}.")
Solution 2: Fix Your Original range() Approach
If you want to stick with range(), adjust the index to match 0-based indexing and fix the print syntax:
names = ['Francisco', 'Marcelle', 'Olivia', 'José', 'Guilherme', 'Maria', 'Arthur', 'Lucas', 'Lurdes', 'Antonio'] # Loop from 0 to 9 (since len(names) is 10) for x in range(len(names)): # The displayed number is x + 1, and we use string concatenation correctly print(names[x] + ", your number on the list is " + str(x + 1) + ".") # Alternatively, use f-strings for cleaner formatting (same result): # print(f"{names[x]}, your number on the list is {x+1}.")
Why These Work:
enumerate(names, start=1)pairs each name with a number starting at 1, so you don't have to do manual index math.range(len(names))ensures we only loop through valid indices (0 to 9), andx + 1converts the 0-based index to the human-friendly 1-based numbering you want.- F-strings (
f"...") make string formatting way easier to read and write than concatenation with+.
Both solutions will output exactly what you want:
Francisco, your number on the list is 1. Marcelle, your number on the list is 2. ... Antonio, your number on the list is 10.
内容的提问来源于stack exchange,提问作者user16625664




