何时使用转发何时使用重定向_何时以及为什么使用

何时使用转发何时使用重定向

重点 (Top highlight)

Very recently, Python 3.8 introduced the use of ‘colon equals’ (:=), which is similar to the equals operator (=). The use of this operator allows for speedup and shortened code, and it’s definitely valuable to understand.

最近,Python 3.8引入了“等号”( := )的用法,类似于等号运算符( = )。 使用此运算符可加快速度并缩短代码,理解它绝对有价值。

This notation comes from a complaint rooted in mathematics. When we write equations in mathematics, we may write something like a=5, a+b=7. Then, one could use simple algebraic manipulation to find that b=2. In this context, the equals sign means equality. The variables a and b are constant numbers, and while their value is not known at the initialization of the problem, it exists and does not change.

这种表示法源自数学方面的抱怨。 当我们用数学写方程式时,我们可能会写类似a=5a+b=7 。 然后,可以使用简单的代数运算来找到b=2 。 在这种情况下,等号表示相等。 变量ab是常数,虽然在问题初始化时不知道它们的值,但它存在并且不会改变。

On the other hand, in mathematics, there exists a different notation for the relationship ‘x is defined to be y’. If one were to write x := y, it is not that x and y share a relationship of quantitative equality but that x is defined to be whatever value y is. It’s more one-way than symmetrical. This is a bit tricky to wrap your head around, but the notation is really only for long lists of variable definitions at the beginning of highly technical research papers.

另一方面,在数学中,对于关系“ x被定义为y ”存在不同的表示法。 如果要写x := y ,则不是xy具有数量相等的关系,而是将x定义为y是什么值。 它比对称更单向。 这有点棘手,但是在高科技研究论文开始之初,该符号实际上仅用于一长串变量定义。

Regardless, in the most recent version of Python 3.8 has emerged the accepted use of :=, or the ‘walrus operator’ (it indeed does look like a horizontal walrus). While it doesn’t address the mathematical complaint in full, it comes from the same idea of defining a variable within an expression in a programming context.

无论如何,在最新版本的Python 3.8中出现了对:=或“海象运算符”(它的确确实像水平海象)的使用。 尽管它不能完全解决数学上的问题,但它来自在编程上下文中在表达式内定义变量的相同思想。

Here was the rationale for the introduction of the walrus operator, from the Python developers:

这是从Python开发人员引入walrus运算符的基本原理:

Naming the result of an expression is an important part of programming, allowing a descriptive name to be used in place of a longer expression, and permitting reuse. Currently, this feature is available only in statement form, making it unavailable in list comprehensions and other expression contexts.- PEP 572

命名表达式的结果是编程的重要部分,它允许使用描述性名称代替较长的表达式,并允许重用。 目前,此功能仅以语句形式可用,从而使其在列表推导和其他表达式上下文中不可用。- PEP 572

This is a very technical way to express a simpler idea, and it will make more sense soon. Let’s take a look at the walrus operator in action.

这是表达简单想法的非常技术性的方法,很快就会有意义。 让我们看看实际的海象运算符。

With the function f defined as f = lambda x : x+2, which simply adds two to any input, consider the following code:

将函数f定义为f = lambda x : x+2 ,该f = lambda x : x+2仅将两个加到任何输入中,请考虑以下代码:

data = [1,2,3,4]
f_data = [y for x in data if (y := f(x)) is not 4]

The result is [3, 5, 6], since these are the results of the function that are not equal to the value four. This is a much more efficient implementation than the alternative, which runs an input through the function twice:

结果为[3, 5, 6] ,因为这些是函数的结果,不等于值4。 这比另一种方法有效得多,后者通过该函数两次运行输入:

f_data = [f(x) for x in data if f(x) is not 4]

Be wary that since version 3.8 is new, some environments that have not been updated may not support it.

请注意,由于3.8版是新的,因此某些尚未更新的环境可能不支持它。

Let’s take another example. There is some text file, named text.txt. It contains three lines with the letters from a-i.

让我们再举一个例子。 有一个名为text.txt文本文件。 它包含三行,带有a - i的字母。

abc
def
ghi

Say that we want to loop through this text file, line by line. There are several ways to do this. We could use a built-in function, .readlines().

假设我们要逐行遍历此文本文件。 有几种方法可以做到这一点。 我们可以使用内置函数.readlines()

for line in open('text.txt','r').readlines():
print(line)

And this isn’t a bad solution — it does what we want. On the other hand, what if you couldn’t use built-in functions? Not all applications will have these sorts of handy functions that do exactly what you want them to do. You could also use the following solution, which splits the text by line:

这不是一个不好的解决方案,它可以满足我们的要求。 另一方面,如果您不能使用内置函数怎么办? 并非所有的应用程序都具有这些方便的功能,它们可以完全满足您的期望。 您还可以使用以下解决方案,按行将文本拆分:

for line in open('text.txt','r').read().split('\n'):
print(line)

This solution also works, but the stacked functions aren’t as simple and clean as they could be. We could write this with the walrus operator:

该解决方案也可以使用,但是堆叠的功能并不像它们可能的那么简单和干净。 我们可以使用海象运算符编写此代码:

while chunk := open('text.txt').read():
print(chunk)

Here, we are simply defining chunk to be the reading of the file. It’s sweet, short, and clean. On the other hand, writing while chunk = open… would be illegal because you can’t create variable assignments while evaluating a separate expression.

在这里,我们只是将chunk定义为文件读取。 香甜,简短,干净。 另一方面, while chunk = open…编写将是非法的,因为您不能在评估单独的表达式时创建变量分配。

As another example, take the given definition of the function f(x) above, adding two to the input. The following construction of a list g is completely valid using the walrus operator:

再举一个例子,采用上面函数f(x)的给定定义,将两个加到输入中。 使用walrus运算符,列表g的以下构造完全有效

g = [y := f(3), y**2, y**3] #contents: [5, 25, 125]

What are we doing here? — y is being defined as f(3), and it is being used immediately after, in the same expression. We could not write something like g = [y=f(3), …], since the assignment of variables using = must be done on its own line and not within another expression. This could alternatively be written with two lines using the standard equals operator:

我们在这里做什么? — y被定义为f(3),并且在同一表达式中紧随其后使用。 我们不能写类似g = [y=f(3), …] ,因为使用=分配变量必须在其自己的行上进行,而不是在另一个表达式内进行。 也可以使用标准的equals运算符用两行代码编写:

y = f(3)
g = [y, y**2, y**3]

By now, the usage of the walrus operator should be relatively clear.

到目前为止,海象运算符的用法应该相对清楚。

:= can be used to assign variables while another expression is being evaluated.

:=可用于在评估另一个表达式时分配变量。

Since variable assignment is the form of var = expr must be written on its own line, the walrus operator allows you to shorten up space by running what would otherwise be an illegal variable assignment within the evaluation of another expression, be it the creation of a list or the reading of a file.

由于变量赋值是var = expr的形式,因此必须在其自己的行上编写,因此walrus运算符允许您通过在另一个表达式的求值过程中运行否则将是非法变量赋值的方式来缩短空间,例如创建a列出或读取文件。

In many ways, the := operator is similar with the defining of placeholder variables, such as for i in range(x):, in which a variable i is initialized within the expression of the for loop. It can be thought of as an extension or generalization of these ‘hidden variable initializations’.

在许多方面, :=运算符与占位符变量的定义类似,例如for i in range(x):的定义,其中i在for循环的表达式内初始化。 可以将其视为这些“隐藏变量初始化”的扩展或概括。

The walrus operator cannot be used for everything, however. The following statements are illegal:

但是,海象运算符不能用于所有功能。 以下陈述是非法的:

a := 3 #must be done with a=3.
a = b := 4 #must be done with a=b=4
a = (b := 4) #legal, but not recommended

It’s worthwhile to explore why the expression a=(b:=4) works. This lies in the realization that b:=4 not only sets b equal to four but returns its value. This is also the reason why the list comprehension statement above (if y := f(x)) is not 4]) works. This statement evaluates b:=4 as an expression, which returns a value. The result: a and b are both set to 4.

值得探讨为什么表达式a=(b:=4)起作用。 这是基于以下认识: b:=4不仅将b设置为等于4,而且还返回其值。 这也是上面的列表理解语句( if y := f(x)) is not 4] )起作用的原因。 该语句将b:= 4评估为一个表达式,该表达式返回一个值。 结果: ab都设置为4。

Taking this further, simply putting parenthesis around the first statement like such — (a := 3) — runs properly, because using parenthesis marks everything inside it as an expression. Walrus operators can only be used inside other expressions.

更进一步,只需将括号放在第一个这样的语句(a := 3) ,因为使用括号将其中的所有内容都标记为表达式。 Walrus运算符只能在其他表达式中使用。

Let’s cross the border into non-pythonic land. Here, we’ll explore some usages of the walrus operator that may be useful but will probably also cause religiously Pythonic disciples to rage with fury.

让我们越过边界进入非Python领域。 在这里,我们将探讨海象运算符的一些用法,这些用法可能很有用,但也可能导致虔诚的Python门徒大为恼火。

Consider a function exponent, which raises a base to an exp.

考虑一个函数exponent ,该exponentexp exponent base

def exponent(base,exp):
return base**exp

What if I wanted to get the value of four to the third power but also store the value of the power (3)? I could use the walrus operator:

如果我想将4的值乘以3的幂,又要存储该幂的值(3)怎么办? 我可以使用海象运算符:

exponent(base=4, exp=(storage:=3))

Three is stored to a variable storage, the function runs perfectly normally, and I saved myself a line of code and some runtime. In large-scale usage of the walrus operator, these savings may add up for some concrete speedups.

三个存储到变量存储中,该函数可以正常运行,并且我为自己节省了一行代码和一些运行时。 在海象运算符的大规模使用中,这些节省可能会增加一些具体的速度。

Walrus operators can be even used in if statements. In the example below, (placeholder:=x) evaluates to whatever the value of x is. If that output is equal to four, it is stored in placeholder anyway. Usually, this kind of usage doesn’t have much practical value, since we are doing redundant assignment (what if x!=4?), but it’s good to know that this is possible.

在if语句中甚至可以使用Walrus运算符。 在下面的示例中, (placeholder:=x)计算得出x的值是什么。 如果该输出等于4,则无论如何将其存储在占位符中。 通常,这种用法没有太多实用价值,因为我们正在进行冗余分配(如果x!=4 ?会怎样),但很高兴知道这是可能的。

x = 4
if (placeholder:=x) == 4:
print(placeholder) #output: 4

As another example of code bordering on unpythonic (has the Python community made its mind up about walrus operators yet?), consider the following completely legal function.

作为与unpythonic接壤的代码的另一个示例(Python社区是否已经考虑过海象运算符?),请考虑以下完全合法的功能。

f = lambda x : (m := x+1) + (m**2)

f(3) returns 20 because (m := x+1) evaluates to 4, and (m**2) evaluates to 16. Their sum equals 20, and it was done in a method that is both so satisfyingly clean but also feels a bit… sneaky. Regardless, the walrus operator is a feature that is, at the very least, helpful.

f(3)返回20,因为(m := x+1)值为4 ,而(m**2)值为16 。 他们的总和等于20,采用的方法既干净又令人满意,但又有点……偷偷摸摸。 无论如何,海象运算符至少是一项有用的功能。

关键点 (Key Points)

  • The walrus operator is denoted :=, and introduced in Python 3.8.

    海象运算符用:=表示,并在Python 3.8中引入。

  • This operator is used for and only for the assignment of variables within another expression. At the very least, it can save one or more lines of code, and at most, it can dramatically speed up the processing of large data.

    此运算符仅用于另一个表达式中的变量分配。 至少,它可以节省一行或多行代码,并且最多可以极大地加快大数据的处理速度。
  • Walrus operators can be used everywhere from loops to functions to list comprehension to if statements to roundabout variable assignment.

    从循环到函数再到列表理解,再到if语句再到回旋变量赋值,Walrus运算符可在任何地方使用。

Read additional technical exceptions, enhancements, and examples on the walrus operator’s PEP page here.

在此处阅读海象运营商的PEP页面上的其他技术例外,增强功能和示例。

翻译自: https://towardsdatascience.com/when-and-why-to-use-over-in-python-b91168875453

何时使用转发何时使用重定向

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值