如何在数字列表上实现模数? [英] How can I implement a modulus on a list of numbers?

查看:67
本文介绍了如何在数字列表上实现模数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数字列表:

6,12,24,25,7,27

6,12,24,25,7,27

我如何才能使模数为26,以便如果列表中出现大于26的数字,则应回到1?

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?

例如,在这种情况下,除27之外,所有数字都应保留为1.

For example, in this situation all numbers should be left alone except 27 and that should become 1.

这是我要运行的代码:

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

但是我得到了错误:

TypeError:%=的不支持的操作数类型:列表"和整数"

TypeError: unsupported operand type(s) for %=: 'list' and 'int'

非常感谢您的帮助.

推荐答案

作为替代方案,如果您愿意/能够将列表转换为Numpy数组,则可以以一种非常简单且pythonic的方式(通过只是将模应用于数组):

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):

>>> 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])

这篇关于如何在数字列表上实现模数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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