【问题标题】:Simplified Dictionary using comprehensions使用推导式的简化字典
【发布时间】: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


【解决方案1】:

没有。据我所知,listdict 理解在您想要获取理解中间元素的值时不起作用。这可能会导致意外输出。

for 循环每次迭代都会更改dict 的内容,而dict 推导式首先创建整个dict,然后将其分配给var。

这是一个列表理解的示例:

# 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

还有一个听写理解

# 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}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-06
    • 1970-01-01
    • 1970-01-01
    • 2021-05-01
    • 1970-01-01
    • 2013-08-17
    • 1970-01-01
    • 2020-08-27
    相关资源
    最近更新 更多