Joh*_*ohn 11 python lookup indexing
现在我正在循环跟踪我的索引
index = 0
for entry in longList:
if entry == 'foo':
print index
index += 1
Run Code Online (Sandbox Code Playgroud)
有一个更好的方法吗?
Bil*_*nch 19
for index, entry in enumerate(longList):
if entry == 'foo':
print index
Run Code Online (Sandbox Code Playgroud)
Chi*_*chi 10
使用enumerate()
内置功能.
for index, entry in enumerate(longList):
if entry == 'foo':
print index
Run Code Online (Sandbox Code Playgroud)
但是,在您的具体情况下,您可以这样做 index = longList.index("foo")
编辑:如果你想在纯Python中尽可能快地找到多个匹配的索引,下面的代码应该可以解决这个问题:
indices = tuple(index for index, element in enumerate(longList) if element=='foo')
Run Code Online (Sandbox Code Playgroud)
我喜欢列表理解:)
[index for (index,entry) in enumerate(longList) if entry == 'foo']
Run Code Online (Sandbox Code Playgroud)
是的,最好的方法是这样做:
longList.index('foo')
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2539 次 |
最近记录: |