簡體   English   中英

如何找到一個項目在列表中第 n 次出現的索引?

[英]How to find the index of the nth time an item appears in a list?

鑒於:

x = ['w', 'e', 's', 's', 's', 'z','z', 's']

s每次出現都出現在以下索引處:

第一名:2
第二名:3
第三名:4
第四名:7

如果我做x.index('s')我會得到第一個索引。

如何獲得第 4 s的索引?

使用列表理解enumerate

>>> x = [ 'w', 'e', 's', 's', 's', 'z','z', 's']
>>> [i for i, n in enumerate(x) if n == 's'][0]
2
>>> [i for i, n in enumerate(x) if n == 's'][1]
3
>>> [i for i, n in enumerate(x) if n == 's'][2]
4
>>> [i for i, n in enumerate(x) if n == 's'][3]
7

如果您不想為每次出現存儲索引,或者想使用任意可迭代對象,則類似於:

from itertools import islice

def nth_index(iterable, value, n):
    matches = (idx for idx, val in enumerate(iterable) if val == value)
    return next(islice(matches, n-1, n), None)

x = [ 'w', 'e', 's', 's', 's', 'z','z', 's']
idx = nth_index(x, 's', 4)
# 7

請注意, next有一個默認值None 您可能希望將其更改為其他內容,或者將其刪除並捕獲StopIteration並將其作為另一個更合適的異常引發(例如ValueError ,以便它與list.index行為有更多聯系)。

獲取項目的索引:

return [index for index, char in enumerate(x) if char == 's']

獲取角色本身:

return [char for index, char in enumerate(x) if char == 's']

或者獲取字符/索引對的元組:(感謝 falsetru 指出一個更簡單的解決方案)

pairs = [(index, char) for index, char in enumerate(x) if char == 's']
def find_nth_character(str1, substr, n):
    """find the index of the nth substr in string str1""" 
    k = 0
    for index, c in enumerate(str1):
        #print index, c, n  # test
        if c == substr:
            k += 1
            if k == n:
                return index


str1 = "B.765.A87_43.Left.9878.xx8"
substr = '.'
occurance = 4

print "%s #%d at index %d" % (substr, occurance, find_nth_character(str1, substr, occurance))

這是使用itertools.count和生成器表達式的更 Pythonic 的方法:

In [24]: def get_nth_index(lst, item, n):
    ...:     c = count()
    ...:     return next(i for i, j in enumerate(x) if j=='s' and next(c) == n-1)

演示:

In [25]: get_nth_index(x, 's', 2)
Out[25]: 3

In [26]: get_nth_index(x, 's', 3)
Out[26]: 4

In [27]: get_nth_index(x, 's', 4)
Out[27]: 7

In [28]: get_nth_index(x, 's', 5)
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-28-fc4e5e8c31ef> in <module>()
----> 1 get_nth_index(x, 's', 5)

<ipython-input-24-5394f79b3c30> in get_nth_index(lst, item, n)
      1 def get_nth_index(lst, item, n):
      2     c = count()
----> 3     return next(i for i, j in enumerate(x) if j=='s' and next(c) == n-1)

StopIteration: 

In [29]: 

如您所見,如果找不到匹配項,它將引發StopIteration異常。 您還可以將默認參數傳遞給next()函數以返回默認值而不是引發異常。

我們可以簡單地擴展內置列表類的功能。 通過繼承它。

In [64]: class List(list):
       :     def __init__(self, *val):
       :         self.extend(list(val))
       :
       :
       :     def findidx(self, val, n=None):
       :         '''return the occurances of an object in a list'''
       :
       :         if n == None:
       :             return [i for i, v in enumerate(self) if v == val]
       :
       :         return [i for i, v in enumerate(self) if v == val][n]

有兩種方法可以使用這個類。 看下面的例子來理解。

In [65]: c = List(4, 5, 6, 7, 2, 5, 4 ,4) # enter the elements of the list as a argument

In [69]: c.findidx(4, 0) # search 4's 0th(1) occurance
Out[69]: 0

In [72]: c.findidx(4, 1) # find 4's 1st(2) occurance
Out[72]: 6

或者

In [66]: c.findidx(4) # find all occurances of 4
Out[66]: [0, 6, 7]

In [67]: c.findidx(4)[0] # first occurance
Out[67]: 0

In [67]: c.findidx(4)[2] # third occurance
Out[67]: 7

In [69]: c[0]# for verification
Out[69]: 4

In [70]: c[7]
Out[70]: 4

`

您可以使用它來查找最后一個位置

其中 a 是數組

t=(a.index(0)+a.count(0))-1

您可以將數字增加到 -2 或 -3 以從最后找到所需數字的位置

注意:必須對列表進行排序。 您可以使用 sort() 對其進行排序

例如: a.sort()

有關列表中的更多內置功能,請單擊此處

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM