本文介绍了“布尔"Python 中的操作(即:和/或运算符)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此方法搜索第一组单词字符(即:[a-zA-Z0-9_]),返回第一个匹配的组或None以防万一失败.

This method searches for the first group of word characters (ie: [a-zA-Z0-9_]), returning the first matched group or None in case of failure.

def test(str):
    m = re.search(r'(\w+)', str)
    if m:
        return m.group(1)
    return None

同样的函数可以改写为:

The same function can be rewritten as:

def test2(str):
    m = re.search(r'(\w+)', str)
    return m and m.group(1)

这是一样的,并且是记录在案的行为;正如此页面明确指出:

This works the same, and is documented behavior; as this page clearly states:

表达式 x 和 y 首先计算 x;如果 x 为假,则返回其值;否则,计算 y 并返回结果值.

然而,作为一个布尔运算符(它甚至在手册上这样说),我希望 返回一个布尔值.结果,当我发现它(如何)起作用时,我惊讶.

However, being a boolean operator (it even says so on the manual), I expected and to return a boolean. As a result, I was astonished when I found out (how) this worked.

还有哪些其他用例,和/或这种相当不直观的实现的基本原理是什么?

What are other use cases of this, and/or what is the rationale for this rather unintuitive implementation?

推荐答案

简洁(因此一旦你习惯了它就会变得清晰,因为毕竟它不会牺牲可读性!-)任何时候你需要检查一些东西或者使用它如果它是真的,或者如果某些东西是假的,则使用另一个值(对于 - 将其反转为 - 我非常故意避免使用实际的关键字或类似的TrueFalse,因为我在谈论每个 对象,而不仅仅是bool!-).

Conciseness (and therefore clarity, as soon as you get used to it, since after all it does not sacrifice readability at all!-) any time you need to check something and either use that something if it's true, or another value if that something is false (that's for and -- reverse it for or -- and I'm very deliberately avoiding the actual keywords-or-the-like True and False, since I'm talking about every object, not just bool!-).

任何计算机屏幕上的垂直空间都是有限的,如果可以选择,最好将其用于有用的可读性辅助工具(文档字符串、注释、有策略地放置空行以分隔块,...)而不是用于转动,例如,一行例如:

Vertical space on any computer screen is limited, and, given the choice, it's best spent on useful readability aids (docstrings, comments, strategically placed empty lines to separate blocks, ...) than in turning, say, a line such as:

inverses = [x and 1.0/x for x in values]

分为六个如:

inverses = []
for x in values:
    if x:
        inverses.append(1.0/x)
    else:
        inverses.append(x)

或更窄的版本.

和/或这样做的理由是什么相当不直观的实现?

远非不直观",初学者经常被一些语言(如标准 Pascal)没有没有指定的评估顺序和短路性质这一事实绊倒andor;Turbo Pascal 与语言标准之间的差异之一,在当时使 Turbo 成为有史以来最受欢迎的 Pascal 方言,正是 Turbo 实现了 andor就像 Python 后来做的一样(而 C 语言更早做了……)

Far from being "unintuitive", beginners regularly were tripped up by the fact that some languages (like standard Pascal) did not specify the order of evaluation and the short-circuiting nature of and and or; one of the differences between Turbo Pascal and the language standard, which back in the day made Turbo the most popular Pascal dialect of all times, was exactly that Turbo implemented and and or much like Python did later (and the C language did earlier...).

这篇关于“布尔"Python 中的操作(即:和/或运算符)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 06:11