【发布时间】:2022-01-03 18:20:52
【问题描述】:
每个人我都想知道一种用 dictcomprehension 简化以下代码的方法:
import random
vowel = "aeiou"
consonants = "bcdfghjklmnpqrstvwxyz"
hand = {}
for i in range(numVowels):
x = VOWELS[random.randrange(0,len(VOWELS))]
hand[x] = hand.get(x, 0) + 1
for i in range(numVowels, n):
x = CONSONANTS[random.randrange(0,len(CONSONANTS))]
hand[x] = hand.get(x, 0) + 1
【问题讨论】:
-
代码应该做什么?
-
使用
random.choices一次性计算列表,然后collections.Counter生成字典。但答案确实是你不能用理解来做到这一点
标签: python dictionary-comprehension