2016-06-24 21 views
-7

我对python很陌生,一直在尝试codewars。有些问题对我来说很难。我试图完成的是,“要知道给定单词中元音的索引,例如,单词super(第二个和第四个字母)中有两个元音。”我真的不明白如何使用索引和/或查找。我需要知道我可以编辑这段代码来找到任何给定单词中元音的位置。有人可以解释如何使用str.index和str.find以及为什么下面的代码是错误的

def vowel_indices(word): 
    word.index("a","i","o","u","e","y") 
    word.find("a","i","o","u","e","y") 
+1

此代码不能运行。你期望它做什么(打印,退货)? – handle

+0

我试图让它返回元音的位置。我知道这并不完整,我只是对接下来要做的事感到困惑。 –

+1

是的,但是你的代码会产生错误信息。你不会陈述那些消息或询问他们。他们提供比“错误”更多的信息来帮助您解决问题。您错误地使用了这些功能。文档告诉你到底做了什么以及如何使用它们。他们只需要一个参数来寻找“单词”。你不使用他们的输出。请看我的答案,并请接受它。 – handle

回答

0

检查文档

围绕打造方法你的代码:

# characters to look for in a list (string would work as well) 
vowels = ["a","i","o","u","e","y"] 

# a function (method) 
def vowel_indices(word): 
    # prepare empty list to collect the positions in 
    hits = [] 

    # test every of your vowels 
    for vowel in vowels: 
     # the function returns the index of vowel in word or -1 if it's not there 
     pos = word.find(vowel) 

     # test for match 
     if pos>0: 
      # collect match in list 
      hits.append(pos) 

    # done, return the list 
    return hits 

# the string to analyse 
word = "super" 

# pass the string to the method and get its return value 
results = vowel_indices(word) 

# output the return value 
print(results) 

输出:

[1, 3] 

这实际上是一个列表对象,但是Python会打印它的元素。


正如@PM 2Ring所指出的那样,这只发现字符串中元音的第一次出现。这有两个原因:

  1. 每个元音只测试一次
  2. str.find()只能找到最左边的匹配(见RFIND()):

    返回指数最低的字符串,其中在在切片s [start:end]内找到子字符串sub。

所以我毫无意义的复杂如下,使其工作代码:

# characters to look for in a list (string would work as well) 
vowels = ["a","i","o","u","e","y"] 

# a function (method) 
def vowel_indices(word): 
    # prepare empty list to collect the positions in 
    hits = [] 
    # test every of your vowels 
    for vowel in vowels: 
     # work on a copy 
     temp = word 
     # look first, give up later 
     while True: 
      # the function returns the index of vowel in word or -1 if it's not there 
      pos = temp.lower().find(vowel) 
      # test for match 
      if pos>0: 
       # collect match in list 
       hits.append(pos) 
       # remove matched vowel from 
       temp = temp[:pos] + " " + temp[pos+1:] 
       print(temp) 
      else: 
       break 

    # done, return the list 
    return hits 

# the string to analyse 
word = "Banana!" 

# pass the string to the method and get its return value 
results = vowel_indices(word) 

# output the return value 
print(results) 

输出

B nana! 
B n na! 
B n n ! 
[1, 3, 5] 
+3

这可行,但效率不高。 –

+0

是的,但容易理解。然而,我没有考虑大写,因此它应该使用'word.lower()。find(元音)' – handle

+0

1.35 s与0.93 s – handle

1

str.index:

S.find()但提高ValueError异常时,未找到的子字符串。

要找到你需要采取一个音符,你已经在你的问题中提到,有些话可以有一个以上的元音(即“枚举”)给定单词的元音,所以这是一个办法对付它们:

def vowel_indices(word): 
    v = ["a","e","u",...] 
    for index, letter in enumerate(word): 
     if letter in v: 
      print("Vowel letter %s, index of [%s]" % (letter, index)) 

也可参考文档Common string operations

Examples for string find in Python

Python String index() Method

How to get the position of a character in Python?

+1

'in'测试也适用于字符串'if'中的字母'',但对一组元音测试会更快一些。 –

4

你不叫str.findstr.index这样。他们都采取的形式

(sub[, start[, end]]) 

,这意味着他们采取了要搜索的子,可能还跟着一个开始索引指定目标字符串从哪里开始搜索,可能还跟着一个参数(独占)结束索引来指定停止搜索的位置。

但是,这不是.find.index的工作。这两种方法都必须对他们搜索的字符串进行线性扫描,并且要找到所有元音都必须循环遍历所有元音,所以你实际上有一个双重循环。

幸运的是,Python提供了一种更高效的方式:将元音放入一个集合中,然后遍历单词中的字母,并测试每个字母是否在元音集合中。测试集成员资格是非常有效的,它不涉及对集合的线性扫描。为了捕捉所有元音,我们需要将大写的&小写元音放入我们的集合中。要跟踪单词中每个元音的位置,我们可以使用enumerate函数。

vowels = set("AEIOUYaeiouy") 
def vowel_indices(word): 
    return [i for i, c in enumerate(word) if c in vowels] 

# Test 
for word in ("super", "AMAZING"): 
    print(word, vowel_indices(word)) 

输出

super [1, 3] 
AMAZING [0, 2, 4] 
+0

使用'set'而不是字符串似乎快了大约10%(函数重命名并与[timeit](https://docs.python.org/3/library/timeit.html#examples)一起使用,如'print(timeit.timeit (“test('Banana!')”,setup =“from __main__ import test”))' – handle

相关问题