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

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

问题描述

给定:

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

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天全站免登陆