问题
I'm a newbie to Python. I'm writing a very simple piece of code to print the contents of a list using 'for' loop with .format()
and I want the output as below, but I'm getting this error:
names = ['David', 'Peter', 'Michael', 'John', 'Bob']
for i in names:
print("{}.{}".format(i, names[i]))
print("{}.{}".format(i,breakfastMenu[i]))
TypeError: list indices must be integers or slices, not str
Expected output I want: 1. David 2. Peter 3. Michael 4. John 5. Bob
Can someone please help me to get that output?
回答1:
names = ['David', 'Peter', 'Michael', 'John', 'Bob']
for i in range (len (names)):
print("{}.{}".format(i + 1, names[i]))
Python list index references cannot be strings. Iterating through the list via a for loop using integers rather than the indexes themselves (which are strings) will solve this issue. This is an example where the error message is very useful in diagnosing the problem.
回答2:
names
is a list
of str
, so, when you iterate over it, you'll get str
values.
for i in names:
print(i + 'other_str') # i is a str
In order to randomly access elements on a list
, you need to specify their index
, which needs to be an int
.
If you want to get the correspondent indices of the elements, while you are iterating over them, you can use Python's enumerate:
for index, name, in enumerate(names):
print('{}.{}'.format(index, names[index]))
Note that you don't really need to access the name by names[index]
because you already get the element when iterating. So, the above is similar to the following:
for index, name in enumerate(names):
print('{}.{}'.format(index, name))
Which outputs:
0.David
1.Peter
2.Michael
3.John
4.Bob
回答3:
Python's for...in statement is like like a foreach in other languages. You want enumerate
to get the indexes.
for i, name in enumerate(names):
print("{}. {}".format(i+1, name))
If you want to print them all on one line, use the end
kwarg.
for i, name in enumerate(names):
print("{}. {}".format(i+1, name), end=" ")
print() # for the final newline
1. David 2. Peter 3. Michael 4. John 5. Bob
回答4:
Well, as per suggested answer from you guys I tried. I got the Expected output
>>> names = ['David', 'Peter', 'Michael', 'John', 'Bob']
>>> for i in range(len(names)):
print('{}.{}'.format(i+1, names[i]))
Output I could see:
1.David
2.Peter
3.Michael
4.John
5.Bob
来源:https://stackoverflow.com/questions/51795644/how-to-print-the-list-in-for-loop-using-format-in-python