且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何找到一个项目在列表中第 n 次出现的索引?

更新时间:2023-01-11 19:54:58

使用 列表理解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

Given:

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

Each occurrence of s appears at the following indices:

1st: 2
2nd: 3
3rd: 4
4th: 7

If I do x.index('s') I will get the 1st index.

How do I get the index of the 4th s?

Using list comprehension and 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