在字典定义中结合理解和键-值列表是否可能?

huangapple go评论62阅读模式
英文:

Is it possible to combine comprehension and key-value listing in dictionary definition?

问题

抱歉,我不能翻译代码部分。以下是代码之外的内容的翻译:

我正在尝试定义一个字典,在这个字典中,一些键-值对可以使用推导式来指定(因为这些键-值对是有公式的),而其他的需要显式指定。由于编码指南的限制,字典的定义必须是单个赋值语句。因此,不能使用多个赋值来组成字典。是否可能将显式的键-值规范与推导式结合起来定义字典?

最小示例:

d = {
    '0': 0x1,
    '0'*r + 'X': 0x100 + r for r in range(2), # 在实际应用中,r 要大得多
    'Y': 0xA
}

期望输出:

>>> d
    {'0': 1, 'X' = 256, '0X' = 257, 'Y' = 10}

错误:

d = {
    '0': 0x1,
    '0'*r + 'X': 0x100 + r for r in range(2),
    
SyntaxError: invalid syntax
英文:

I am trying to define a dictionary wherein some key-value pairs can be specified using comprehension (because these pairs are formulaic), while others need to be specified explicitly. Due to a coding guideline restriction, the dictionary definition needs to be a single assignment statement. Therefore, no multiple assignments to compose the dictionary. Is it possible to combine explicit key-value specification along with comprehension to define the dictionary?

Minimal example:

d = {
    '0': 0x1,
    '0'*r + 'X': 0x100 + r for r in range(2), # r is much larger in real-world application
    'Y': 0xA
}

Expected output:

>>> d
    {'0': 1, 'X' = 256, '0X' = 257, 'Y' = 10}

Error:

d = {
    '0': 0x1,
    '0'*r + 'X': 0x100 + r for r in range(2),
    
SyntaxError: invalid syntax

答案1

得分: 3

你可以使用字典解包语法 **PEP 448)在一个表达式中合并两个或多个字典,参见:https://stackoverflow.com/questions/38987/how-do-i-merge-two-dictionaries-in-a-single-expression-in-python

d = {'0': 0x1, **inner, 'Y': 0xA}

在这种情况下,内部字典是通过字典推导式创建的:

{'0'*r + 'X': 0x100 + r for r in range(2)}

因此,结果表达式为:

d = {
    '0': 0x1,
    **{'0'*r + 'X': 0x100 + r for r in range(2)},
    'Y': 0xA
}
英文:

You can merge two or more dictionaries in one expression by using the dictionary unpacking syntax ** (PEP 448), see: https://stackoverflow.com/questions/38987/how-do-i-merge-two-dictionaries-in-a-single-expression-in-python

d = {'0': 0x1, **inner, 'Y': 0xA}

In this case, the inner dictionary is created by a dictionary comprehension:

{'0'*r + 'X': 0x100 + r for r in range(2)}

So the resulting expression is:

d = {
    '0': 0x1,
    **{'0'*r + 'X': 0x100 + r for r in range(2)},
    'Y': 0xA
}

huangapple
  • 本文由 发表于 2023年6月2日 04:23:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76385467.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定