做什么 &蟒蛇的意思 [英] What does & mean in python

查看:70
本文介绍了做什么 &蟒蛇的意思的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了以下代码

numdigits = len(cardNumber)
oddeven = numdigits & 1

这里到底发生了什么?我不确定&"是什么正在做.

what exactly is going on here? I'm not sure what the "&" is doing.

推荐答案

答案

& 符号是一个按位 AND 运算符.与 1 一起使用,它基本上屏蔽了值以提取最低位,或者换句话说会告诉您该值是偶数还是奇数.

Answer

The & symbol is a bitwise AND operator. Used with 1, it basically masks the value to extract the lowest bit, or in other words will tell you if the value is even or odd.

有关更多信息,请参阅:http://wiki.python.org/moin/BitwiseOperators

For more information, see: http://wiki.python.org/moin/BitwiseOperators

添加此部分是因为这个答案得到了一些人的喜爱

将一个值与 1 进行 AND 运算的原因一开始可能并不明显.

The reason why ANDing a value with 1 tells if the value is odd or even may not be obvious at first.

数字的二进制表示本质上是从最右边的数字开始向左移动的 YES 或 NO 的一系列 YES 或 NO 的总和,其中 1, 2, 4, 8, ...

The binary representation of a number is essentially the sum of a series of YES or NO for each power of 2 moving leftward starting in the rightmost digit with 1, 2, 4, 8, ...

以这种方式表示任何数字只有一种方式.例如.数字 13(以 10 为底)可以用二进制写成1101"(或十六进制写成 0xD,但这不是重点).看这里:

There is only one way to represent any number in this way. E.g. the number 13 (base 10) can be written in binary as "1101" (or hexadecimal as 0xD, but that's beside the point). See here:

    1   1   0   1
    x   x   x   x
    8   4   2   1
    =   =   =   =
    8 + 4 + 0 + 1  =  13

请注意,除了最右边的二进制数字外,所有其他 1 数字都会将偶数(即 2 的倍数)加到总和上.因此,获得奇数最终和的唯一方法是从最右边的数字中添加奇数 1.因此,如果我们好奇一个数是奇数还是偶数,我们可以查看它的二进制表示并忽略除最右边的数字之外的所有内容.

Notice that aside from the rightmost binary digit, all other 1 digits will add an even number (i.e. a multiple of 2) to the sum. So the only way to get an odd final sum is to add that odd 1 from the rightmost digit. So if we're curious if a number is odd or even, we can look at its binary representation and ignore everything except for the rightmost digit.

为此,我们使用按位 AND 运算符.二进制值1表示为1:

To do this, we use the bitwise AND operator. The value 1 in binary is expressed as 1:

    0   0   0   1
    x   x   x   x
    8   4   2   1
    =   =   =   =
    0 + 0 + 0 + 1  =  1

将一个值与 1 进行 AND 运算,如果该值的最右边位被设置,则结果为 1,如果没有,则结果为 0.

ANDing a value with 1 like this will result in 1 if the value's rightmost bit is set, and 0 if it is not.

并且因为 0 在大多数语言中通常被认为是假",非零值被认为是真",我们可以简单地说:

And because 0 is generally considered "false" in most languages, and non-zero values considered "true", we can simply say as a shortcut:

if (value & 1): do_something_with_odd_value()...

这篇关于做什么 &蟒蛇的意思的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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