基于真/假值的Python优雅的分配 [英] Python elegant assignment based on True/False values

查看:125
本文介绍了基于真/假值的Python优雅的分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个变量我想这取决于三个布尔值来设置。最直接的办法就是if语句后跟一系列elifs的:

I have a variable I want to set depending on the values in three booleans. The most straight-forward way is an if statement followed by a series of elifs:

if a and b and c:
    name = 'first'
elif a and b and not c:
    name = 'second'
elif a and not b and c:
    name = 'third'
elif a and not b and not c:
    name = 'fourth'
elif not a and b and c:
    name = 'fifth'
elif not a and b and not c:
    name = 'sixth'
elif not a and not b and c:
    name = 'seventh'
elif not a and not b and not c:
    name = 'eighth'

这是一个有点尴尬,我不知道是否有处理这个问题的一个更Python的方式。一对夫妇的想法浮现在脑海中。

This is a bit awkward, and I'm wondering if there's a more Pythonic way to handle this problem. A couple of ideas come to mind.


  1. 字典破解:

  1. Dictionary hack:

name = {a and b and c: 'first',
        a and b and not c: 'second',
        a and not b and c: 'third',
        a and not b and not c: 'fourth',
        not a and b and c: 'fifth',
        not a and b and not c: 'sixth',
        not a and not b and c: 'seventh',
        not a and not b and not c: 'eighth'}[True]


我把它称为一个黑客,因为我不是太热衷键七是假,并覆盖对方。

I call it a hack because I'm not too wild about seven of the keys being False and overriding each other.


  1. 和/或魔术

  1. And/or magic

name = (a and b and c and 'first' or
        a and b and not c and 'second' or
        a and not b and c and 'third' or
        a and not b and not c and 'fourth' or
        not a and b and c and 'fifth' or
        not a and b and not c and 'sixth' or
        not a and not b and c and 'seventh' or
        not a and not b and not c and 'eighth')


这工作,因为Python的AND和OR返回进行评估的最后一个值,但是你要知道,为了了解这个本来离奇code。

This works because Python ands and ors return the last value to be evaluated, but you have to know that in order to understand this otherwise bizarre code.

这三个选项都不是非常令人满意的。你有什么建议?

None of these three options is very satisfying. What do you recommend?

推荐答案

您可以把A,B和C的三个位,当放在一起形成0和7之间的数字。然后,你可以有数组值[第一,第二,......第八届']并使用比特值的偏移量数组。这将只是code两行(一到比特组装成一个值从0-7,以及一个查找数组中的值)。

You can think of a, b, and c as three bits that when put together form a number between 0 and 7. Then, you can have an array of the values ['first', 'second', ... 'eighth'] and use the bit value as an offset into the array. This would just be two lines of code (one to assemble the bits into a value from 0-7, and one to lookup the value in the array).

这里的code:

nth = ['eighth', 'seventh', 'sixth', 'fifth', 'fourth', 'third', 'second', 'first']
nth[(a and 4 or 0) | (b and 2 or 0) | (c and 1 or 0)]

这篇关于基于真/假值的Python优雅的分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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