查找第一个元素不等于特定值的索引



我想找到字符串中不等于给定值的第一个元素的索引

伪代码:

string='111111234131986'
string.find(!='1')

结果:

6

这是一个使用lstrip()len()的非常简单的解决方案:

len(string) - len(string.lstrip("1"))

如果string为空或完全由"1"组成,则此解决方案返回len(string)

假设你想要第一个不'1'的元素,我们可以使用next()enumerate()

>>> string='111111234131986'
>>> next((i for i, x in enumerate(string) if x!='1'), None)
6

你可以试试这个,

string='111111234131986' #required string
for items in string: #loop to iterate over the elements to find the odd one
if items != '1':
print items
Output for this:
2
3
4
3
9
8
6

相关内容

最新更新