简体   繁体   English

在两个值之间切换变量的大多数Python方法

[英]Most pythonic way to toggle a variable between two values

I have a variable, p, that is the output of a regular expression match and is guaranteed to be either 'true' or 'false' in any mixed case. 我有一个变量p,它是一个正则表达式匹配项的输出,在任何混合情况下都保证为“ true”或“ false”。 If 'true' I want it to be 'FALSE' and if 'false' I want it to be 'TRUE'. 如果为“ true”,我希望它为“ FALSE”;如果为“ false”,我希望它为“ TRUE”。 The end result is always uppercase. 最终结果始终是大写。

I have thought of the following four methods. 我想到了以下四种方法。 Which is the most pythonic or is there a better one? 哪个是最pythonic的,还是有更好的pythonic的?

p=['TRUE','FALSE'][eval(p.capitalize())]
p=(not eval(p.capitalize())).__repr__().upper()
p='FALSE' if eval(p.capitalize()) else 'TRUE'
p={'TRUE':'FALSE','FALSE':'TRUE'}[p.upper()]

IMO, the most pythonic way isn't with eval , or with dunders, or using a 2-element list indexing, it's a simple if-else conditional (or ternary): IMO,最Python的方式不是使用eval ,dunders或使用2元素列表索引,这是一种简单的if-else条件(或三进制)条件:

p = 'TRUE' if p.upper() == 'FALSE' else 'FALSE'

It doesn't use hacks or trickery, it is simple and (more importantly) readable. 它不使用黑客手段或欺骗手段,它很简单,并且(更重要的是)可读性强。

@ cs95的解决方案是可行的方法,但这是(IMO)可接受的(尽管可读性较差,而且可能更复杂)替代方案:

p = str(p.upper() == "FALSE").upper()

EDITED:How about 编辑:怎么样

p=str(p.lower()!="true").upper()

No loops, no if, no complex functions. 没有循环,没有,没有复杂的功能。 Just change type functions. 只需更改类型功能。 Short and simple ;) 简短;;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM