使用字典理解来查找字符串中的元音?

Using dictionary comprehension to find vowels in string?

假设S = "Tea Lemon CoffEE cAke".lower()

    { x:y.count('aeoiu') for x in S.split() for y in 'aeoiu' if y in 'aeoiu' }

这个输出是:

    {'cake': 0, 'tea': 0, 'lemon': 0, 'coffee': 0}

为什么它给我的是 0 而不是每个单词中的元音数量? 我是 python 的新手,希望得到一些提示。完全不是在寻找直接的答案。

我想你想这样做:

{ x: sum(x.count(y) for y in 'aeoiu') for x in S.split() }

输出:

{'coffee': 3, 'cake': 2, 'lemon': 2, 'tea': 2}

您的代码正在计算字符串 'aeoiu' 在 y 中出现的次数,该次数始终为零。另请注意 for y in 'aeoiu' if y in 'aeoiu' 是多余的,您不需要 if.