Reputation: 11
everyone i'd like to know a way to simplify the following code with a 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
Upvotes: 0
Views: 61
Reputation: 515
No. As far as I know, list
and dict
comprehensions don't work when you want to get the value of elements in the middle of the comprehension. This can cause unexpected outputs.
The for
loop changes the contents of the dict
with each iteration, while a dict
comprehension first creates the entire dict
, and then assigns it to the var.
Here's an example with a list comprehension:
# for loop
>>> l = [1] * 20
>>> for i in range(1, 20):
... l[i] = l[i - 1] + l[i]
...
>>> l
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
# list comprehension
>>> l = [1] * 20
>>> l = [ l[i - 1] + l[1] for i in range(1, 20) ]
>>> l
[2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2
And a dict comprehension
# for loop
>>> s = "abcdefghij"
>>> d = {}
>>> for i in range(10):
... d[s[i]] = d.get(s[i - 1], 0) + 1
...
>>> d
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'j': 10}
# dict comprehension
>>> s = "abcdefghij"
>>> d = {}
>>> d = {s[i]: d.get(s[i - 1], 0) + 1 for i in range(10)}
>>> d
{'a': 1, 'b': 1, 'c': 1, 'd': 1, 'e': 1, 'f': 1, 'g': 1, 'h': 1, 'i': 1, 'j': 1}
Upvotes: 1