python2d列表理解中的passbyreference问题

2024-05-18 20:15:18 发布

您现在位置:Python中文网/ 问答频道 /正文

把这句话记下来:

case_forms = {'plural': {'nominative': 'dni', 'locative': 'dniach'}, 
              'singular': {'instrumental': 'dniem', 'vocative': 'dzie\xc5\x84'}}

我想得到所有可用作case_forms[a][b]的(a,b)密钥对的列表。你知道吗

没问题,对吧?双重列表理解。在哈斯克尔总是这样做:

[(number, case_name) for case_name in case_dict.keys() for number, case_dict in case_forms.items()]

但这不会产生你所期望的结果:

[('plural', 'instrumental'),
 ('singular', 'instrumental'),
 ('plural', 'vocative'),
 ('singular', 'vocative')]

我想知道如何解决这个问题。再多巧妙地放置[:]似乎也不会奏效。你知道吗


Tags: nameinnumber列表forformsdictcase
1条回答
网友
1楼 · 发布于 2024-05-18 20:15:18

这个怎么样:

[ (number, case_name) for number, case_dict in case_forms.items() for case_name in case_dict.keys() ]

编辑为参考@胡安帕.阿里维拉加关于为什么我的例子行为怪异的评论:

Python 2 list comprehensions have leaky scope, and it's not using the case_dict you think it is, it's using the case_dict from a previous comprehension (that leaked into the external scope)

Start a new interpreter session and you'll get the NameError

相关问题 更多 >

    热门问题