简体   繁体   English

如何在数字列表上实现模数?

[英]How can I implement a modulus on a list of numbers?

I have a list of numbers: 我有一个数字列表:

6,12,24,25,7,27 6,12,24,25,7,27

How can I make it so that there is modulus at 26 so that if numbers greater than 26 appear in the list it should go back to 1? 我如何才能使模数为26,以便如果列表中出现的数字大于26,则应回到1?

For example, in this situation all numbers should be left alone except 27 and that should become 1. 例如,在这种情况下,除27之外,所有数字都应保留为1。

This is the code I'm trying to run: 这是我要运行的代码:

message = zip(message, newkeyword)
positions = [(alphabet.find(m), alphabet.find(n)) for m, n in message]
sums = [alphabet.find(m) + alphabet.find(n) for m, n in message]
#sums is were the numbers are stored
sums%=26

But I get the error: 但是我得到了错误:

TypeError: unsupported operand type(s) for %=: 'list' and 'int' TypeError:%=不支持的操作数类型:“ list”和“ int”

Any help is greatly appreciated. 任何帮助是极大的赞赏。

The modulo operator can only be applied to two numbers, not to a whole list. 取模运算符只能应用于两个数字,不能应用于整个列表。 You have to apply it to each item, like this: 您必须将其应用于每个项目,如下所示:

mod_sums = [s % 26 for s in sums]

Using a list comprehension you iterate through all numbers in the sums. 使用列表推导,您可以迭代求和中的所有数字。 In the new mod_sums list you save the number s modulo 26. 在新的mod_sums列表中,将数字s模26保存。

This basically is the same as: 这基本上与以下内容相同:

mod_sums = []
for s in sums:
    mod_sums.append(s % 26)

Only written in a cleaner and more pythonic way. 仅以更简洁 ,更Python化的方式编写。

You could also add the modulo directly into the first list comprehension: 您也可以将模直接添加到第一个列表理解中:

sums = [(alphabet.find(m) + alphabet.find(n)) % 26 for m, n in message]

As an alternative, if you are willing/able to convert your list to a Numpy array you can achieve this in a really simple and pythonic way (by just applying the modulo to the array): 或者,如果您愿意/能够将列表转换为Numpy数组,则可以以一种非常简单和Python的方式(仅对数组应用模数)来实现:

>>> import numpy as np
>>> a = np.array([6,12,24,25,7,27])
>>> a
array([ 6, 12, 24, 25,  7, 27])
>>> a%26
array([ 6, 12, 24, 25,  7,  1])

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

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