wa7*_*a7d 0 python dictionary-comprehension
假设 S = "Tea Lemon CoffEE cAke".lower()
{ x:y.count('aeoiu') for x in S.split() for y in 'aeoiu' if y in 'aeoiu' }
Run Code Online (Sandbox Code Playgroud)
这个输出是:
{'cake': 0, 'tea': 0, 'lemon': 0, 'coffee': 0}
Run Code Online (Sandbox Code Playgroud)
为什么它给我0而不是每个单词中的元音数量?我是python的新手,我会很感激一些提示.完全不寻找直接的答案.
我想你想这样做:
{ x: sum(x.count(y) for y in 'aeoiu') for x in S.split() }
Run Code Online (Sandbox Code Playgroud)
哪个输出:
{'coffee': 3, 'cake': 2, 'lemon': 2, 'tea': 2}
Run Code Online (Sandbox Code Playgroud)
您的代码计算字符串'aeoiu'出现的次数y,始终为零.另请注意,这for y in 'aeoiu' if y in 'aeoiu'是多余的,您不需要if.
| 归档时间: |
|
| 查看次数: |
251 次 |
| 最近记录: |