For in In lists
I'm trying to do something like that, in a nutshell...
house = ['yes', 'no','maybe']
x = range(3)
for x in house
print[x]
I want to loop over a list but I got 'type error: list indices must be integers not Tags.' How can I achieve this ?
If you want to iterate over a list, you don't need an index at all:
for x in house:
print x # prints every house
If you want an index, you can use different approaches:
# generate indexes on the fly
for i, a_house in enumerate(house):
print i, a_house # prints 0 yes, 1 no, 2 maybe
# access by index
# you may change boundaries or reverse order, e.g. try range(2, -1 , -1)
for i in range(3):
print house[i]
Just think on plain english:
for item in house:
print item
that is one of python powers.
what you want is something more like this:
house = ['yes', 'no', 'maybe']
for x in range(3):
print house[x]
No range need...
for item in house: print item
精彩评论