问题
I'm wondering how to print specific items from a list e.g. given:
li = [1,2,3,4]
I want to print just the 3rd and 4th within a loop and I have been trying to use some kind of for-loop like the following:
for i in range (li(3,4)):
print (li[i])
However I'm Getting all kinds of error such as:
TypeError: list indices must be integers, not tuple.
TypeError: list object is not callable
I've been trying to change ()
for []
and been shuffling the words around to see if it would work but it hasn't so far.
回答1:
Using slice notation you can get the sublist of items you want:
>>> li = [1,2,3,4]
>>> li[2:]
[3, 4]
Then just iterate over the sublist:
>>> for item in li[2:]:
... print item
...
3
4
回答2:
You should do:
for i in [2, 3]:
print(li[i])
By range(n)
, you are getting [0, 1, 2, ..., n-1]
By range(m, n)
, you are getting [m, m+1, ..., n-1]
That is why you use range
, getting a list
of indices.
It is more recommended to use slicing
like other fellows showed.
回答3:
li(3,4)
will try to call whatever li
is with the arguments 3
and 4
. As a list is not callable, this will fail. If you want to iterate over a certain list of indexes, you can just specify it like that:
for i in [2, 3]:
print(li[i])
Note that indexes start at zero, so if you want to get the 3
and 4
you will need to access list indexes 2
and 3
.
You can also slice the list and iterate over the lists instead. By doing li[2:4]
you get a list containing the third and fourth element (i.e. indexes i
with 2 <= i < 4
). And then you can use the for loop to iterate over those elements:
for x in li[2:4]:
print(x)
Note that iterating over a list will give you the elements directly but not the indexes.
来源:https://stackoverflow.com/questions/20609376/printing-specific-items-out-of-a-list