如何更简洁地找到缺失值? [英] How can I find the missing value more concisely?

查看:89
本文介绍了如何更简洁地找到缺失值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码检查xy是不同的值(变量xyz只能具有值abc)和如果是这样,请将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屋!

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