如何更简洁地找到缺失值? [英] How can I find the missing value more concisely?
问题描述
以下代码检查x
和y
是不同的值(变量x
,y
,z
只能具有值a
,b
或c
)和如果是这样,请将z
设置为第三个字符:
The following code checks if x
and y
are distinct values (the variables x
, y
, z
can only have values a
, b
, or c
) and if so, sets z
to the third character:
if x == 'a' and y == 'b' or x == 'b' and y == 'a':
z = 'c'
elif x == 'b' and y == 'c' or x == 'c' and y == 'b':
z = 'a'
elif x == 'a' and y == 'c' or x == 'c' and y == 'a':
z = 'b'
是否可以以更简洁,可读和有效的方式做到这一点?
Is is possible to do this in a more, concise, readable and efficient way?
推荐答案
z = (set(("a", "b", "c")) - set((x, y))).pop()
我假设您的代码中的三种情况之一成立.在这种情况下,集合set(("a", "b", "c")) - set((x, y))
将包含一个元素,由pop()
返回.
I am assuming that one of the three cases in your code holds. If this is the case, the set set(("a", "b", "c")) - set((x, y))
will consist of a single element, which is returned by pop()
.
如Raymond Hettinger在评论中所建议,您还可以使用元组拆包从集合中提取单个元素:
As suggested by Raymond Hettinger in the comments, you could also use tuple unpacking to extract the single element from the set:
z, = set(("a", "b", "c")) - set((x, y))
这篇关于如何更简洁地找到缺失值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!