具有多个参数的list.index()有什么作用?

时间:2017-03-21 09:36:24

标签: python arrays indexing

当我找到this post时,我正在寻找一种在列表中找到第n个匹配项的方法:

  

我不能肯定这是最快的方式,但我想它会非常好:

i = -1
for j in xrange(n):
    i = x.index(True, i + 1)
     

答案是我。

x:布尔人名单

n:出现次数

True:元素搜索

虽然我了解此代码的一般行为,但i = x.index(True, i + 1)到底做了什么?确切地说,第二个参数的作用是什么?我在index()上找不到任何包含多个参数的示例。

编辑:我正在使用Python 2.7

3 个答案:

答案 0 :(得分:3)

可以在the documentation for Python 3.6中找到,第二个参数用于表示起始索引。

文档中使用的示例显示了使用第二个参数与省略它之间的区别:

>>> fruits.index('banana')
3
>>> fruits.index('banana', 4)  # Find next banana starting a position 4
6

第三个参数也可用,表示结束索引。

答案 1 :(得分:1)

第二个参数将搜索范围限制为给定列表中在该位置<或>之后。还有第三个参数可以避免在列表结束之前搜索列表。

s.index(x[, i[, j]])

index of the first occurrence of x in s (at or after index i and before index j)

来自:https://docs.python.org/3/library/stdtypes.html#common-sequence-operations

答案 2 :(得分:1)

list.index(x[, start[, end]])

在值为x的第一个项的列表中返回从零开始的索引。如果没有这样的项,则引发ValueError。

可选参数start和end被解释为切片表示法,用于将搜索限制为列表的特定子序列。返回的索引是相对于完整序列的开头而不是start参数计算的。

访问this documentation link了解详情

fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']

fruits.index('banana')
  
    
      

3

    
  
fruits.index('banana', 4)  # Find next banana starting a position 4
  
    
      

6