词典理解中的三元表达 [英] Ternary expression in dictionary comprehension

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

问题描述

我正在尝试反转字典.在许多键具有相同值的情况下,新键(旧值)应与一组新值(旧键)相关联.我解决了问题,但是我试图使用字典理解和一些辅助方法进行重构.

I'm trying to invert a dictionary. In the case of many keys having the same value, the new key (old value) should associate with a set of the new values (old keys). I solved the problem, but I'm trying to refactor using dictionary comprehension, and some helper methods.

def has_unique_value(k):
    return d.values().count(d[k]) == 1

def keys_with_same_value_as_key(k):
    return set([key for key in d.keys() if d[key] == d[k]])

print( {d[k]:k if has_unique_value(k) else d[k]:keys_with_same_value_as_key(k) for k in d.keys()} )

但是,这会引发语法错误

However, this raises a syntax error

print( {d[k]:k if has_unique_value(k) else d[k]:keys_with_same_value_as_key(k) for k in d} )
                                               ^
SyntaxError: invalid syntax

希望该代码中的对齐正确.它应指向else子句中的第二个:.知道这里有什么吗?我已经尝试了尽可能多的括号形式.

Hopefully the alignment in that code works right. It should point to the second :, in the else clause. Any idea what's up here? I've tried as many forms of parenthesizing as I can conceive.

推荐答案

关闭!

以下代码

d = {'a': 'x', 'b': 'y', 'c': 'x'}

def has_unique_value(k):
    return d.values().count(d[k]) == 1

def keys_with_same_value_as_key(k):
    return set([key for key in d.keys() if d[key] == d[k]])

print( {d[k]:k if has_unique_value(k) else keys_with_same_value_as_key(k) for k in d.keys()} )

产生

{'y': 'b', 'x': set(['a', 'c'])}

唯一的区别是第二个d[k]:被删除.

The only difference is the second d[k]: is removed.

通常,三元表达式看起来像

In general, the ternary expression looks like

a = val_if_true if test else val_if_false

与您所拥有的不相近:

a = val_if_true if test else a = val_if_false

您可以指定三元表达式的值应在开始处到哪一次.

You specify where the value from the ternary expression should go once, at the beginning.

RE:评论中的问题

这绝对仍然是对字典的理解.

This is still definitely a dictionary comprehension.

基本上是在做以下事情:

It's basically doing the following:

m = {}
for k in d.keys():
    orig_key = k
    orig_val = d[k]

    if has_unique_value(k):
        m[orig_val] = orig_key
    else:
        m[orig_val] = keys_with_same_value_as_key(orig_key)

print m

唯一的区别是,在字典理解中,m字典不保留在名称空间中(而我用来澄清代码的变量orig_keyorig_val则不存在).

The only difference is that, in the dictionary comprehension, the m dictionary is not kept in the namespace (and the variables orig_key and orig_val I used to clarify the code never exist).

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

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