【问题标题】:Sorting a list based on number of vowels in the words in python根据python中单词中元音的数量对列表进行排序
【发布时间】:2014-01-14 14:01:18
【问题描述】:

如何根据python中单词中元音的数量对列表进行排序?

我没有在任何网站上找到答案。 单词按元音个数降序排列。

【问题讨论】:

    标签: python list sorting python-2.7


    【解决方案1】:

    使用sortedlist.sort

    用计算元音数量的函数指定key。 (函数的返回值作为比较键。)

    reverse=True 参数传递给降序。

    >>> word_list = ['banana', 'apple', 'pineapple']
    >>> sorted(word_list,
    ...        key=lambda word: sum(ch in 'aeiou' for ch in word),
    ...        reverse=True)
    ['pineapple', 'banana', 'apple']
    

    【讨论】:

    • 小细节; ('a', 'e', 'i', 'o', 'u') 可以写成'aeiou'
    • @EelcoHoogendoorn,你是对的。我更新了代码。谢谢。
    • 你能解释一下“key=lambda word: sum(ch in ('a', 'e', 'i', 'o', 'u') for ch in word)”什么“单词”是这里的意思吗?
    • @user3194076,列表的每一项都传递给key函数。 word 是项目。 (lambda 的一个参数)
    【解决方案2】:

    你可以通过创建如下两个函数来做到这一点

    def vowel_count_test(string):
        count=0
        for z in string:
            if z in ['a','e','i','o','u']:
                count=count+1
        return count
    def sort_by_vowel_count(words):
        return words.sort(key=vowel_count_test,reverse=True)
    

    【讨论】:

      猜你喜欢
      • 2014-07-31
      • 2017-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-17
      • 1970-01-01
      • 2014-03-12
      相关资源
      最近更新 更多