[英]python Occurring letters in a string. Index Counting
只是尝试编写一个基本函数,该函数应为此单词打印某个字母的索引号。
下面是写的函数。 它只是打印出我给我的字母的第一个索引
def ind_fnd(word, char):
"""
>>> ind_fnd("apollo", "o")
'2 5 '
>>> ind_fnd("apollo", "l")
'3 4 '
>>> ind_fnd("apollo", "n")
''
>>> ind_fnd("apollo", "a")
'0'
"""
index = 0
while index < len(word):
if word [index] == char:
return index
index += 1
以上是我需要的功能类型。 我不知道是什么。
您不应该立即返回索引,因为那样会终止该函数。 相反,请按照以下步骤操作:
def ind_fnd(word, char):
"""
>>> ind_fnd("apollo", "o")
'2 5 '
>>> ind_fnd("apollo", "l")
'3 4 '
>>> ind_fnd("apollo", "n")
''
>>> ind_fnd("apollo", "a")
'0'
"""
index = 0
indices = []
while index < len(word):
if word [index] == char:
indices.append(index)
index += 1
return indices
这将创建所有索引的列表,然后将其返回。
>>> ind_fnd('apollo','o')
[2,5]
>>> ind_fnd('eevee','e')
[0,1,3,4]
>>> ind_fnd('hello, 'z')
[]
尝试这个,
>>> def find(word,char):
result=[]
for index,i in enumerate(word):
if i==char:
result.append(index)
return result
>>> print find("this is example string",'i')
[2, 5, 19]
我会做:
def ind_find(s, c):
return (i for i, x in enumerate(s) if x == c)
演示:
>>> list(ind_find('apollo', 'o'))
[2, 5]
代码不起作用的原因是,一旦找到第一个索引,您将return
。 我的代码通过构造所有索引的list
来解决此问题,然后在适用时返回该list
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.