我如何使用元音计数对列表进行排序尝试了这一点..但是不对

时间:2014-01-12 07:33:07

标签: python list sorting

def conut(words):
    vowels = "aeiou"
    s= 0
    for a in words[0:5]:
        for x in vowels[0:len(vowels)]:
            s = s + (a.count(x))
words= ["elephant","apple","kat"]
b = words.sort(key = conut(words))

3 个答案:

答案 0 :(得分:1)

您可以使用str.count(sub[, start[, end]])http://docs.python.org/2/library/stdtypes.html#str.count

def vowelscount(word):
    return sum([word.count(x) for x in 'aeiou'])

test = ['aaa', 'aeiouoiea', 'aiuola']
sorted(test, key=vowelscount)

答案 1 :(得分:0)

您希望sorted使用自定义比较:

def num_vowels(word):
     count = 0
     for c in word:
         if c in "aeiou":
             count += 1
     return count

>>>> test = ["aeaeaeaeaeaeae","ace","aeiouios"]
>>>> sorted(test, key=num_vowels)
['ace', 'aeiouios', 'aeaeaeaeaeaeae']

答案 2 :(得分:0)

您可以使用Counter来计算字符串中char的数量。然后总结你感兴趣的那些,在这种情况下是元音。

>>> from collections import Counter
>>> def vowelcounts(word):
...     vowels = "aeiou"
...     return sum([j for i,j in Counter(word).items() if i in vowels])
... 
>>> test = ["aeaeaeaeaeaeae","ace","aeiouios"]
>>> sorted(test, key=vowelcounts)
['ace', 'aeiouios', 'aeaeaeaeaeaeae']