词典理解中的if-else [英] if-else in a dictionary comprehension

查看:92
本文介绍了词典理解中的if-else的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在dictcomp中使用else语句(如果是,如何使用?)?

Is it possible to use the else statement (and if yes, how?) in a dictcomp?

不可能将else用作理解本身的一部分(请参见

It is not possible to use else as part of the comprehension itself (see this) but at least in list and set comprehensions it is possible to use the conditional_expression (see this).

listcomp的示例是在这里.

我的示例代码是:

converters = {"id": int}
rows = [{"id": "1", "name": "foo"}, {"id": "2", "name": "bar"}]
for row in rows:
    row = {k: converters[k](v) if k in converters else k:v for k,v in row.items()}
    print(row)

这不起作用.

奇怪的是,

row = {k: converters[k](v) if k in converters for k, v in row.items()}也不起作用,尽管应该没问题.

row = {k: converters[k](v) if k in converters for k, v in row.items()} does not work either, although it should be ok.

row = {k: converters[k](v) for k, v in row.items() if k in converters}确实有效,但这不是我想要的结果.
如上文所述,row = {k: converters[k](v) for k, v in row.items() if k in converters else k:v}应该不起作用.

row = {k: converters[k](v) for k, v in row.items() if k in converters} does work,but this is not the result I want.
row = {k: converters[k](v) for k, v in row.items() if k in converters else k:v} should not work, as I pointed out above.

我知道我可以通过使用两个dictcomp来绕过该问题,但是我想知道为什么这不起作用.

I know that I could bypass the problem by using two dictcomps, but I want to know why this does not work.

推荐答案

这是因为该条件适用于字典的值,而不适用于键值对,即其求值为:

That's because the conditional applies for the value of the dictionary, not for the key value pair, i.e it is evaluated as:

row = {k: (converters[k](v) if k in converters else k:v) for k,v in row.items()}

k:v在语法上无效,它仅在一对大括号内或函数签名中有效(因此,您可以将k:v放在方括号中并固定SyntaxError,但是这会改变结尾结果).

and k:v is not syntactically valid here, it's only valid inside a pair of curly brackets or in a function signature (so, you could place k:v in brackets and fix the SyntaxError but, that changes the end result).

解决方案是简单地提供条件中的值,因为那会改变:

The solution is to simply supply the value in the conditional since that is what changes:

row = {k: converters[k](v) if k in converters else v for k,v in row.items()}

当然,另一种选择是将元组提供给dict构造函数:

Another option, of course, is to instead supply tuples to the dict constructor:

row = dict((k, converters[k](v)) if k in converters else (k,v) for k,v in row.items())

这篇关于词典理解中的if-else的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆