如何找到项目在列表中出现的第n次索引? [英] How to find the index of the nth time an item appears in a list?

查看:128
本文介绍了如何找到项目在列表中出现的第n次索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于:

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

每次出现 s 出现在以下指数中:



第一名:2

第二名:3名
3rd:4

4th:7



如果我做 x.index('s')我将获得第一个索引。



如何获得第4个 s的索引?<使用列表理解 枚举

 >>> 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

这篇关于如何找到项目在列表中出现的第n次索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆