In the tutorial there is an example for finding prime numbers:
在教程中有一个查找素数的示例:
>>> for n in range(2, 10):
... for x in range(2, n):
... if n % x == 0:
... print(n, 'equals', x, '*', n//x)
... break
... else:
... # loop fell through without finding a factor
... print(n, 'is a prime number')
...
I understand that the double ==
is a test for equality, but I don't understand the if n % x
part. Like I can verbally walk through each part and say what the statement does for the example. But I don't understand how the percentage sign falls in.
我理解double ==是对相等性的测试,但我不理解if n%x部分。就像我可以口头地浏览每个部分并说出该声明对该示例的作用。但我不明白百分号是如何落入的。
What does if n % x
actually say?
如果n%x实际说什么呢?
8 个解决方案
#1
46
Modulus operator; gives the remainder of the left value divided by the right value. Like:
模数算子;给左值的余数除以右值。喜欢:
3 % 1
would equal zero (since 3 divides evenly by 1)
3%1将等于零(因为3将1均分为1)
3 % 2
would equal 1 (since dividing 3 by 2 results in a remainder of 1).
3%2将等于1(因为将3除以2导致余数为1)。
#2
94
The % does two things, depending on its arguments. In this case, it acts as the modulo operator, meaning when its arguments are numbers, it divides the first by the second and returns the remainder. 34 % 10 == 4
since 34 divided by 10 is three, with a remainder of four.
%根据其参数做两件事。在这种情况下,它充当模运算符,这意味着当它的参数是数字时,它将第一个除以第二个并返回余数。 34%10 == 4因为34除以10是3,其余为4。
If the first argument is a string, it formats it using the second argument. This is a bit involved, so I will refer to the documentation, but just as an example:
如果第一个参数是字符串,则使用第二个参数对其进行格式化。这有点涉及,所以我将参考文档,但作为一个例子:
>>> "foo %d bar"%5
'foo 5 bar'
However, the string formatting behavior is supplemented as of Python 3.1 in favor of the string.format()
mechanism:
但是,从Python 3.1开始补充字符串格式化行为,支持string.format()机制:
The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly). Using the newer
str.format()
interface helps avoid these errors, and also provides a generally more powerful, flexible and extensible approach to formatting text.这里描述的格式化操作表现出各种怪癖,导致许多常见错误(例如无法正确显示元组和字典)。使用较新的str.format()接口有助于避免这些错误,并且还提供了一种通常更强大,灵活和可扩展的格式化文本的方法。
And thankfully, almost all of the new features are also available from python 2.6 onwards.
值得庆幸的是,几乎所有的新功能都可以从python 2.6开始提供。
#3
6
While this is slightly off-topic, since people will find this by searching for "percentage sign in Python" (as I did), I wanted to note that the % sign is also used to prefix a "magic" function in iPython: https://ipython.org/ipython-doc/3/interactive/tutorial.html#magic-functions
虽然这有点偏离主题,因为人们会通过搜索“Python中的百分号”(就像我做的那样)找到这个,我想要注意,%符号也用于在iPython中为“魔术”函数添加前缀:https ://ipython.org/ipython-doc/3/interactive/tutorial.html#magic-functions
#4
1
In python 2.6 the '%' operator performed a modulus. I don't think they changed it in 3.0.1
在python 2.6中,'%'运算符执行了模数。我不认为他们在3.0.1中改变了它
The modulo operator tells you the remainder of a division of two numbers.
模运算符告诉您两个数的除法的余数。
#5
1
It checks if the modulo of the division. For example, in the case you are iterating over all numbers from 2 to n and checking if n is divisible by any of the numbers in between. Simply put, you are checking if a given number n is prime. (Hint: You could check up to n/2).
它检查是否为模的模。例如,如果您正在迭代从2到n的所有数字,并检查n是否可被中间任何数字整除。简而言之,您正在检查给定数字n是否为素数。 (提示:你最多可以检查n / 2)。
#6
1
The modulus operator. The remainder when you divide two number.
模数运算符。除以两个数字时的余数。
For Example:
例如:
>>> 5 % 2 = 1 # remainder of 5 divided by 2 is 1
>>> 7 % 3 = 1 # remainer of 7 divided by 3 is 1
>>> 3 % 1 = 0 # because 1 divides evenly into 3
#7
0
Blockquote x % n ==0 which means the x/n and the value of reminder will taken as a result and compare with zero....
Blockquote x%n == 0这意味着x / n和提醒值将作为结果并与零进行比较....
example: 4/5==0
例如:4/5 == 0
4/5 reminder is 1
4/5提醒是1
1==0 (False)
1 == 0(假)
#8
0
What does the percentage sign mean?
百分号是什么意思?
It's an operator in Python that can mean several things depending on the context. A lot of what follows was already mentioned (or hinted at) in the other answers but I thought it could be helpful to provide a more extensive summary.
它是Python中的一个运算符,根据上下文可能意味着几个东西。在其他答案中已经提到(或暗示过)后面的很多内容,但我认为提供更广泛的摘要可能会有所帮助。
%
for Numbers: Modulo operation / Remainder / Rest
The percentage sign is an operator in Python. It's described as:
百分号是Python中的运算符。它被描述为:
x % y remainder of x / y
So it gives you the remainder/rest that remains if you "floor divide" x by y. Generally (at least in Python) given a number x
and a divisor y
:
所以它给你剩下的剩余/休息,如果你把x除以“x”。通常(至少在Python中)给出一个数字x和一个除数y:
x == y * (x // y) + (x % y)
For example if you divide 5 by 2:
例如,如果将5除以2:
>>> 5 // 2
2
>>> 5 % 2
1
>>> 2 * (5 // 2) + (5 % 2)
5
In general you use the modulo operation to test if a number divides evenly by another number, that's because multiples of a number modulo that number returns 0:
通常,您使用模运算来测试数字是否均匀地除以另一个数字,这是因为以该数字为模的数字的倍数返回0:
>>> 15 % 5 # 15 is 3 * 5
0
>>> 81 % 9 # 81 is 9 * 9
0
That's how it's used in your example, it cannot be a prime if it's a multiple of another number (except for itself and one), that's what this does:
这就是它在你的例子中使用的方式,如果它是另一个数字的倍数(除了它自己和一个),它就不能成为素数,这就是它的作用:
if n % x == 0:
break
If you feel that n % x == 0
isn't very descriptive you could put it in another function with a more descriptive name:
如果你觉得n%x == 0不是很具描述性,你可以将它放在另一个具有更具描述性名称的函数中:
def is_multiple(number, divisor):
return number % divisor == 0
...
if is_multiple(n, x): break
if is_multiple(n,x):break
Instead of is_multiple
it could also be named evenly_divides
or something similar. That's what is tested here.
而不是is_multiple,它也可以命名为uniformity_divides或类似的东西。这是在这里测试的。
Similar to that it's often used to determine if a number is "odd" or "even":
类似于它通常用于确定数字是“奇数”还是“偶数”:
def is_odd(number):
return number % 2 == 1
def is_even(number):
return number % 2 == 0
And in some cases it's also used for array/list indexing when wrap-around (cycling) behavior is wanted, then you just modulo the "index" by the "length of the array" to achieve that:
并且在某些情况下,当需要环绕(循环)行为时,它也用于数组/列表索引,然后您只需通过“数组长度”对“索引”进行模数化即可实现:
>>> l = [0, 1, 2]
>>> length = len(l)
>>> for index in range(10):
... print(l[index % length])
0
1
2
0
1
2
0
1
2
0
Note that there is also a function for this operator in the standard library operator.mod
(and the alias operator.__mod__
):
请注意,标准库operator.mod(以及别名运算符.__ mod__)中还有一个此运算符的函数:
>>> import operator
>>> operator.mod(5, 2) # equivalent to 5 % 2
1
But there is also the augmented assignment %=
which assigns the result back to the variable:
但是还有增强赋值%=将结果赋给变量:
>>> a = 5
>>> a %= 2 # identical to: a = a % 2
>>> a
1
%
for strings: printf
-style String Formatting
For strings the meaning is completely different, there it's one way (in my opinion the most limited and ugly) for doing string formatting:
对于字符串来说,意思是完全不同的,那就是进行字符串格式化的一种方式(在我看来,最有限和最丑陋):
>>> "%s is %s." % ("this", "good")
'this is good'
Here the %
in the string represents a placeholder followed by a formatting specification. In this case I used %s
which means that it expects a string. Then the string is followed by a %
which indicates that the string on the left hand side will be formatted by the right hand side. In this case the first %s
is replaced by the first argument this
and the second %s
is replaced by the second argument (good
).
这里,字符串中的%表示占位符,后跟格式规范。在这种情况下,我使用%s,这意味着它需要一个字符串。然后该字符串后跟一个%,表示左侧的字符串将由右侧格式化。在这种情况下,第一个%s被第一个参数this替换,第二个%s被第二个参数(good)替换。
Note that there are much better (probably opinion-based) ways to format strings:
请注意,格式化字符串有更好的(可能是基于意见的)方法:
>>> "{} is {}.".format("this", "good")
'this is good.'
%
in Jupyter/IPython: magic commands
To quote the docs:
引用文档:
To Jupyter users: Magics are specific to and provided by the IPython kernel. Whether magics are available on a kernel is a decision that is made by the kernel developer on a per-kernel basis. To work properly, Magics must use a syntax element which is not valid in the underlying language. For example, the IPython kernel uses the
%
syntax element for magics as%
is not a valid unary operator in Python. While, the syntax element has meaning in other languages.对于Jupyter用户:Magics是IPython内核特有的并由其提供。内核是否可以在内核上使用魔术是由内核开发人员在每个内核基础上做出的决定。要正常工作,Magics必须使用在底层语言中无效的语法元素。例如,IPython内核对magics使用%语法元素,因为%不是Python中有效的一元运算符。而语法元素在其他语言中具有意义。
This is regularly used in Jupyter notebooks and similar:
这经常用于Jupyter笔记本和类似的:
In [1]: a = 10
b = 20
%timeit a + b # one % -> line-magic
54.6 ns ± 2.7 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
In [2]: %%timeit # two %% -> cell magic
a ** b
362 ns ± 8.4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
The %
operator on arrays (in the NumPy / Pandas ecosystem)
The %
operator is still the modulo operator when applied to these arrays, but it returns an array containing the remainder of each element in the array:
应用于这些数组时,%运算符仍然是模运算符,但它返回一个数组,其中包含数组中每个元素的其余部分:
>>> import numpy as np
>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> a % 2
array([0, 1, 0, 1, 0, 1, 0, 1, 0, 1])
Customizing the %
operator for your own classes
Of course you can customize how your own classes work when the %
operator is applied to them. Generally you should only use it to implement modulo operations! But that's a guideline, not a hard rule.
当然,您可以在应用%运算符时自定义自己的类的工作方式。通常,您应该只使用它来实现模运算!但这是一个指导方针,而不是一个硬性规则。
Just to provide a simple example that shows how it works:
只是提供一个简单的例子来说明它是如何工作的:
class MyNumber(object):
def __init__(self, value):
self.value = value
def __mod__(self, other):
print("__mod__ called on '{!r}'".format(self))
return self.value % other
def __repr__(self):
return "{self.__class__.__name__}({self.value!r})".format(self=self)
This example isn't really useful, it just prints and then delegates the operator to the stored value, but it shows that __mod__
is called when %
is applied to an instance:
这个例子并不真正有用,它只是打印然后将运算符委托给存储的值,但它显示当%应用于实例时调用__mod__:
>>> a = MyNumber(10)
>>> a % 2
__mod__ called on 'MyNumber(10)'
0
Note that it also works for %=
without explicitly needing to implement __imod__
:
请注意,它也适用于%=而无需明确需要实现__imod__:
>>> a = MyNumber(10)
>>> a %= 2
__mod__ called on 'MyNumber(10)'
>>> a
0
However you could also implement __imod__
explicitly to overwrite the augmented assignment:
但是,您也可以显式实现__imod__以覆盖扩充的赋值:
class MyNumber(object):
def __init__(self, value):
self.value = value
def __mod__(self, other):
print("__mod__ called on '{!r}'".format(self))
return self.value % other
def __imod__(self, other):
print("__imod__ called on '{!r}'".format(self))
self.value %= other
return self
def __repr__(self):
return "{self.__class__.__name__}({self.value!r})".format(self=self)
Now %=
is explicitly overwritten to work in-place:
现在%=被明确覆盖以便就地工作:
>>> a = MyNumber(10)
>>> a %= 2
__imod__ called on 'MyNumber(10)'
>>> a
MyNumber(0)
#1
46
Modulus operator; gives the remainder of the left value divided by the right value. Like:
模数算子;给左值的余数除以右值。喜欢:
3 % 1
would equal zero (since 3 divides evenly by 1)
3%1将等于零(因为3将1均分为1)
3 % 2
would equal 1 (since dividing 3 by 2 results in a remainder of 1).
3%2将等于1(因为将3除以2导致余数为1)。
#2
94
The % does two things, depending on its arguments. In this case, it acts as the modulo operator, meaning when its arguments are numbers, it divides the first by the second and returns the remainder. 34 % 10 == 4
since 34 divided by 10 is three, with a remainder of four.
%根据其参数做两件事。在这种情况下,它充当模运算符,这意味着当它的参数是数字时,它将第一个除以第二个并返回余数。 34%10 == 4因为34除以10是3,其余为4。
If the first argument is a string, it formats it using the second argument. This is a bit involved, so I will refer to the documentation, but just as an example:
如果第一个参数是字符串,则使用第二个参数对其进行格式化。这有点涉及,所以我将参考文档,但作为一个例子:
>>> "foo %d bar"%5
'foo 5 bar'
However, the string formatting behavior is supplemented as of Python 3.1 in favor of the string.format()
mechanism:
但是,从Python 3.1开始补充字符串格式化行为,支持string.format()机制:
The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly). Using the newer
str.format()
interface helps avoid these errors, and also provides a generally more powerful, flexible and extensible approach to formatting text.这里描述的格式化操作表现出各种怪癖,导致许多常见错误(例如无法正确显示元组和字典)。使用较新的str.format()接口有助于避免这些错误,并且还提供了一种通常更强大,灵活和可扩展的格式化文本的方法。
And thankfully, almost all of the new features are also available from python 2.6 onwards.
值得庆幸的是,几乎所有的新功能都可以从python 2.6开始提供。
#3
6
While this is slightly off-topic, since people will find this by searching for "percentage sign in Python" (as I did), I wanted to note that the % sign is also used to prefix a "magic" function in iPython: https://ipython.org/ipython-doc/3/interactive/tutorial.html#magic-functions
虽然这有点偏离主题,因为人们会通过搜索“Python中的百分号”(就像我做的那样)找到这个,我想要注意,%符号也用于在iPython中为“魔术”函数添加前缀:https ://ipython.org/ipython-doc/3/interactive/tutorial.html#magic-functions
#4
1
In python 2.6 the '%' operator performed a modulus. I don't think they changed it in 3.0.1
在python 2.6中,'%'运算符执行了模数。我不认为他们在3.0.1中改变了它
The modulo operator tells you the remainder of a division of two numbers.
模运算符告诉您两个数的除法的余数。
#5
1
It checks if the modulo of the division. For example, in the case you are iterating over all numbers from 2 to n and checking if n is divisible by any of the numbers in between. Simply put, you are checking if a given number n is prime. (Hint: You could check up to n/2).
它检查是否为模的模。例如,如果您正在迭代从2到n的所有数字,并检查n是否可被中间任何数字整除。简而言之,您正在检查给定数字n是否为素数。 (提示:你最多可以检查n / 2)。
#6
1
The modulus operator. The remainder when you divide two number.
模数运算符。除以两个数字时的余数。
For Example:
例如:
>>> 5 % 2 = 1 # remainder of 5 divided by 2 is 1
>>> 7 % 3 = 1 # remainer of 7 divided by 3 is 1
>>> 3 % 1 = 0 # because 1 divides evenly into 3
#7
0
Blockquote x % n ==0 which means the x/n and the value of reminder will taken as a result and compare with zero....
Blockquote x%n == 0这意味着x / n和提醒值将作为结果并与零进行比较....
example: 4/5==0
例如:4/5 == 0
4/5 reminder is 1
4/5提醒是1
1==0 (False)
1 == 0(假)
#8
0
What does the percentage sign mean?
百分号是什么意思?
It's an operator in Python that can mean several things depending on the context. A lot of what follows was already mentioned (or hinted at) in the other answers but I thought it could be helpful to provide a more extensive summary.
它是Python中的一个运算符,根据上下文可能意味着几个东西。在其他答案中已经提到(或暗示过)后面的很多内容,但我认为提供更广泛的摘要可能会有所帮助。
%
for Numbers: Modulo operation / Remainder / Rest
The percentage sign is an operator in Python. It's described as:
百分号是Python中的运算符。它被描述为:
x % y remainder of x / y
So it gives you the remainder/rest that remains if you "floor divide" x by y. Generally (at least in Python) given a number x
and a divisor y
:
所以它给你剩下的剩余/休息,如果你把x除以“x”。通常(至少在Python中)给出一个数字x和一个除数y:
x == y * (x // y) + (x % y)
For example if you divide 5 by 2:
例如,如果将5除以2:
>>> 5 // 2
2
>>> 5 % 2
1
>>> 2 * (5 // 2) + (5 % 2)
5
In general you use the modulo operation to test if a number divides evenly by another number, that's because multiples of a number modulo that number returns 0:
通常,您使用模运算来测试数字是否均匀地除以另一个数字,这是因为以该数字为模的数字的倍数返回0:
>>> 15 % 5 # 15 is 3 * 5
0
>>> 81 % 9 # 81 is 9 * 9
0
That's how it's used in your example, it cannot be a prime if it's a multiple of another number (except for itself and one), that's what this does:
这就是它在你的例子中使用的方式,如果它是另一个数字的倍数(除了它自己和一个),它就不能成为素数,这就是它的作用:
if n % x == 0:
break
If you feel that n % x == 0
isn't very descriptive you could put it in another function with a more descriptive name:
如果你觉得n%x == 0不是很具描述性,你可以将它放在另一个具有更具描述性名称的函数中:
def is_multiple(number, divisor):
return number % divisor == 0
...
if is_multiple(n, x): break
if is_multiple(n,x):break
Instead of is_multiple
it could also be named evenly_divides
or something similar. That's what is tested here.
而不是is_multiple,它也可以命名为uniformity_divides或类似的东西。这是在这里测试的。
Similar to that it's often used to determine if a number is "odd" or "even":
类似于它通常用于确定数字是“奇数”还是“偶数”:
def is_odd(number):
return number % 2 == 1
def is_even(number):
return number % 2 == 0
And in some cases it's also used for array/list indexing when wrap-around (cycling) behavior is wanted, then you just modulo the "index" by the "length of the array" to achieve that:
并且在某些情况下,当需要环绕(循环)行为时,它也用于数组/列表索引,然后您只需通过“数组长度”对“索引”进行模数化即可实现:
>>> l = [0, 1, 2]
>>> length = len(l)
>>> for index in range(10):
... print(l[index % length])
0
1
2
0
1
2
0
1
2
0
Note that there is also a function for this operator in the standard library operator.mod
(and the alias operator.__mod__
):
请注意,标准库operator.mod(以及别名运算符.__ mod__)中还有一个此运算符的函数:
>>> import operator
>>> operator.mod(5, 2) # equivalent to 5 % 2
1
But there is also the augmented assignment %=
which assigns the result back to the variable:
但是还有增强赋值%=将结果赋给变量:
>>> a = 5
>>> a %= 2 # identical to: a = a % 2
>>> a
1
%
for strings: printf
-style String Formatting
For strings the meaning is completely different, there it's one way (in my opinion the most limited and ugly) for doing string formatting:
对于字符串来说,意思是完全不同的,那就是进行字符串格式化的一种方式(在我看来,最有限和最丑陋):
>>> "%s is %s." % ("this", "good")
'this is good'
Here the %
in the string represents a placeholder followed by a formatting specification. In this case I used %s
which means that it expects a string. Then the string is followed by a %
which indicates that the string on the left hand side will be formatted by the right hand side. In this case the first %s
is replaced by the first argument this
and the second %s
is replaced by the second argument (good
).
这里,字符串中的%表示占位符,后跟格式规范。在这种情况下,我使用%s,这意味着它需要一个字符串。然后该字符串后跟一个%,表示左侧的字符串将由右侧格式化。在这种情况下,第一个%s被第一个参数this替换,第二个%s被第二个参数(good)替换。
Note that there are much better (probably opinion-based) ways to format strings:
请注意,格式化字符串有更好的(可能是基于意见的)方法:
>>> "{} is {}.".format("this", "good")
'this is good.'
%
in Jupyter/IPython: magic commands
To quote the docs:
引用文档:
To Jupyter users: Magics are specific to and provided by the IPython kernel. Whether magics are available on a kernel is a decision that is made by the kernel developer on a per-kernel basis. To work properly, Magics must use a syntax element which is not valid in the underlying language. For example, the IPython kernel uses the
%
syntax element for magics as%
is not a valid unary operator in Python. While, the syntax element has meaning in other languages.对于Jupyter用户:Magics是IPython内核特有的并由其提供。内核是否可以在内核上使用魔术是由内核开发人员在每个内核基础上做出的决定。要正常工作,Magics必须使用在底层语言中无效的语法元素。例如,IPython内核对magics使用%语法元素,因为%不是Python中有效的一元运算符。而语法元素在其他语言中具有意义。
This is regularly used in Jupyter notebooks and similar:
这经常用于Jupyter笔记本和类似的:
In [1]: a = 10
b = 20
%timeit a + b # one % -> line-magic
54.6 ns ± 2.7 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
In [2]: %%timeit # two %% -> cell magic
a ** b
362 ns ± 8.4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
The %
operator on arrays (in the NumPy / Pandas ecosystem)
The %
operator is still the modulo operator when applied to these arrays, but it returns an array containing the remainder of each element in the array:
应用于这些数组时,%运算符仍然是模运算符,但它返回一个数组,其中包含数组中每个元素的其余部分:
>>> import numpy as np
>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> a % 2
array([0, 1, 0, 1, 0, 1, 0, 1, 0, 1])
Customizing the %
operator for your own classes
Of course you can customize how your own classes work when the %
operator is applied to them. Generally you should only use it to implement modulo operations! But that's a guideline, not a hard rule.
当然,您可以在应用%运算符时自定义自己的类的工作方式。通常,您应该只使用它来实现模运算!但这是一个指导方针,而不是一个硬性规则。
Just to provide a simple example that shows how it works:
只是提供一个简单的例子来说明它是如何工作的:
class MyNumber(object):
def __init__(self, value):
self.value = value
def __mod__(self, other):
print("__mod__ called on '{!r}'".format(self))
return self.value % other
def __repr__(self):
return "{self.__class__.__name__}({self.value!r})".format(self=self)
This example isn't really useful, it just prints and then delegates the operator to the stored value, but it shows that __mod__
is called when %
is applied to an instance:
这个例子并不真正有用,它只是打印然后将运算符委托给存储的值,但它显示当%应用于实例时调用__mod__:
>>> a = MyNumber(10)
>>> a % 2
__mod__ called on 'MyNumber(10)'
0
Note that it also works for %=
without explicitly needing to implement __imod__
:
请注意,它也适用于%=而无需明确需要实现__imod__:
>>> a = MyNumber(10)
>>> a %= 2
__mod__ called on 'MyNumber(10)'
>>> a
0
However you could also implement __imod__
explicitly to overwrite the augmented assignment:
但是,您也可以显式实现__imod__以覆盖扩充的赋值:
class MyNumber(object):
def __init__(self, value):
self.value = value
def __mod__(self, other):
print("__mod__ called on '{!r}'".format(self))
return self.value % other
def __imod__(self, other):
print("__imod__ called on '{!r}'".format(self))
self.value %= other
return self
def __repr__(self):
return "{self.__class__.__name__}({self.value!r})".format(self=self)
Now %=
is explicitly overwritten to work in-place:
现在%=被明确覆盖以便就地工作:
>>> a = MyNumber(10)
>>> a %= 2
__imod__ called on 'MyNumber(10)'
>>> a
MyNumber(0)