### 如何在列表中获取项目的位置？

``````testlist = [1,2,3,5,3,1,2,1,6]
for item in testlist:
if item == 1:
print position
``````

#### 12 个答案:

`````` [i for i,x in enumerate(testlist) if x == 1]
``````

``````>>> testlist
[1, 2, 3, 5, 3, 1, 2, 1, 6]
>>> [i for i,x in enumerate(testlist) if x == 1]
[0, 5, 7]
``````

``````>>> for i in [i for i,x in enumerate(testlist) if x == 1]:
...     print i
...
0
5
7
``````

``````>>> (i for i,x in enumerate(testlist) if x == 1)
<generator object at 0x6b508>
>>> for i in (i for i,x in enumerate(testlist) if x == 1):
...     print i
...
0
5
7
``````

``````>>> gen = (i for i,x in enumerate(testlist) if x == 1)
>>> for i in gen: print i
...
0
5
7
``````

``````print testlist.index(element)
``````

``````if element in testlist:
print testlist.index(element)
``````

``````print(testlist.index(element) if element in testlist else None)
``````

``````try:
print testlist.index(element)
except ValueError:
pass
``````

``````testlist = [1,2,3,5,3,1,2,1,6]
for position, item in enumerate(testlist):
if item == 1:
print position
``````

``````for i in xrange(len(testlist)):
if testlist[i] == 1:
print i
``````

xrange而不是请求的范围（请参阅注释）。

``````try:
id = testlist.index('1')
print testlist[id]
except ValueError:
``````

``````[x for x in range(len(testlist)) if testlist[x]==1]
``````

``````testlist = [1,2,3,5,3,1,2,1,6]
position=0
for i in testlist:
if i == 1:
print(position)
position=position+1
``````

``````lookingFor = 1
i = 0
index = 0
try:
while i < len(testlist):
index = testlist.index(lookingFor,i)
i = index + 1
print index
except ValueError: #testlist.index() cannot find lookingFor
pass
``````

``certain condition``

``````input_list = [[1,2,3,4,5,6,7],[1,3,7]]
series1 = input_list[0]
series2 = input_list[1]
idx_list = list(map(lambda item: series1.index(item) if item in series1 else None, series2))
print(idx_list)
``````

``````testlist = [1,2,3,5,3,1,2,1,6]
for position, item in enumerate(testlist):
if item == 1:
print position
``````

``````from Tkinter import *
listbox.curselection()
``````

（'0'，）（虽然更高版本的Tkinter可能会返回一个int列表）

``````testlist = [1,2,3,5,3,1,2,1,6]
for id, value in enumerate(testlist):
if id == 1:
print testlist[id]
``````