我在列表上进行迭代,如果符合某个条件,我想打印出项目的索引.我该怎么做?
例:
testlist = [1,2,3,5,3,1,2,1,6]
for item in testlist:
if item == 1:
print position
Run Code Online (Sandbox Code Playgroud)
Cha*_*tin 269
嗯.这里有一个列表理解的答案,但它已经消失了.
这里:
[i for i,x in enumerate(testlist) if x == 1]
Run Code Online (Sandbox Code Playgroud)
例:
>>> testlist
[1, 2, 3, 5, 3, 1, 2, 1, 6]
>>> [i for i,x in enumerate(testlist) if x == 1]
[0, 5, 7]
Run Code Online (Sandbox Code Playgroud)
更新:
好的,你想要一个生成器表达式,我们将有一个生成器表达式.这是for循环中的列表理解:
>>> for i in [i for i,x in enumerate(testlist) if x == 1]:
... print i
...
0
5
7
Run Code Online (Sandbox Code Playgroud)
现在我们将构建一个发电机......
>>> (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
Run Code Online (Sandbox Code Playgroud)
并且足够好,我们可以将它分配给变量,并从那里使用它...
>>> gen = (i for i,x in enumerate(testlist) if x == 1)
>>> for i in gen: print i
...
0
5
7
Run Code Online (Sandbox Code Playgroud)
并认为我曾经写过FORTRAN.
mmj*_*mmj 157
以下怎么样?
print testlist.index(element)
Run Code Online (Sandbox Code Playgroud)
如果您不确定要查找的元素是否实际位于列表中,您可以添加初步检查,例如
if element in testlist:
print testlist.index(element)
Run Code Online (Sandbox Code Playgroud)
要么
print(testlist.index(element) if element in testlist else None)
Run Code Online (Sandbox Code Playgroud)
或者"pythonic方式",我不太喜欢,因为代码不太清楚,但有时效率更高,
try:
print testlist.index(element)
except ValueError:
pass
Run Code Online (Sandbox Code Playgroud)
zda*_*dan 40
使用枚举:
testlist = [1,2,3,5,3,1,2,1,6]
for position, item in enumerate(testlist):
if item == 1:
print position
Run Code Online (Sandbox Code Playgroud)
jak*_*ber 10
for i in xrange(len(testlist)):
if testlist[i] == 1:
print i
Run Code Online (Sandbox Code Playgroud)
xrange而不是请求的范围(请参阅注释).
小智 5
这是执行此操作的另一种方法:
try:
id = testlist.index('1')
print testlist[id]
except ValueError:
print "Not Found"
Run Code Online (Sandbox Code Playgroud)
尝试以下方法:
testlist = [1,2,3,5,3,1,2,1,6]
position=0
for i in testlist:
if i == 1:
print(position)
position=position+1
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
505406 次 |
| 最近记录: |