简体   繁体   English

Python - 不懂运算符 - 指数

[英]Python - don't understand operator - exponent

I'm going through the Python Institute's tutorial, and they have an expression in a for loop, which taking a list of 1,2,3... produces output of 1,4,9,16.我正在阅读 Python Institute 的教程,他们在 for 循环中有一个表达式,它采用 1,2,3... 的列表生成 1,4,9,16 的 output。 So, it appears to me, it's squaring each element.所以,在我看来,它是对每个元素进行平方。

elem **= 2元素 **= 2

I don't understand what the "=" is doing there.我不明白“=”在那里做什么。 Shouldn't it be written elem ** 2?不应该写成elem ** 2吗? Is it just an alternative way to write it?它只是另一种编写方式吗?

It appears to work in code.它似乎适用于代码。

def listUpdater(lst):
updList = []
for elem in lst:
    elem **= 2
    updList.append(elem)
return updList


def main():
    l = [1, 2, 3, 4, 5]
    print(listUpdater(l))

In this link you have a nice overview of Python operators with an alternative way to write them too.此链接中,您可以很好地了解 Python 运算符以及另一种编写它们的方法。

Essentially the combination of an operator like ** with a = means that first the operator ist executed and the result of that is assigned to the variable on the left side.本质上,像**这样的运算符与=的组合意味着首先执行该运算符,并将其结果分配给左侧的变量。

So in your case elem is squared and the result is saved in the same elem and in the next line appended to updList .因此,在您的情况下, elem 是平方的,结果保存在同一个 elem 和附加到updList的下一行中。

An alternative way of writing it would be elem = elem ** 2 .另一种写法是elem = elem ** 2

The '=' is applying the changes to the variable 'elem', without the '=', it will give you the square of it, but the variable will not change, it will stay not squared. '=' 将更改应用到变量 'elem',没有 '=',它会给你它的平方,但变量不会改变,它不会平方。

The '=' sign changes the elem variable. '=' 符号更改 elem 变量。

Instead of writing:而不是写:

elem = elem**2

You can instead write:您可以改写:

elem **= 2

The **= operator applies the operation of power with the arguments from both sides of the operator and saves it to the variable. **=运算符从运算符两边对arguments进行幂运算,并保存到变量中。 This is the same as doing elem = elem ** 2 .这与执行elem = elem ** 2相同。

Similarly, if you wanted to increment a variable by 1, you could do i+=1 .类似地,如果您想将一个变量递增 1,您可以执行i+=1 The value of i would be incremented. i的值将增加。

Basically you could write elem **2 It will work fine.基本上你可以写elem **2它会工作得很好。 you could add this line print(elem **@2) and see its working.您可以添加此行print(elem **@2)并查看其工作情况。 The reason to add "=" sign is to resign the value that you have computed by elem**2 into elem.添加“=”符号的原因是将您通过elem**2计算的值重新分配给 elem。

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

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