abs*_*urd 3 python list python-2.7
如果我有以下列表
vowels = ["a","e","i","o","u"]
Run Code Online (Sandbox Code Playgroud)
和另一个清单
words = ["happiness", "yellow"]
Run Code Online (Sandbox Code Playgroud)
我如何计算每个单词中的元音数量,即幸福= 3,黄色= 2?
使用列表理解:
>>> vowels = ["a","e","i","o","u"]
>>> words = ["happiness", "yellow"]
>>> [sum(c in vowels for c in word) for word in words]
[3, 2]
Run Code Online (Sandbox Code Playgroud)
如果要在单词和出现之间进行映射,请使用字典理解:
>>> {word: sum(c in vowels for c in word) for word in words}
{'happiness': 3, 'yellow': 2}
Run Code Online (Sandbox Code Playgroud)
转换vowels为set将使其更有效.
| 归档时间: |
|
| 查看次数: |
3715 次 |
| 最近记录: |