gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 23:06:42 25 4
gpt4 key购买 nike

我有一个数字列表:

6,12,24,25,7,27

我怎样才能使模数为 26,这样如果列表中出现大于 26 的数字,它应该返回到 1?

例如,在这种情况下,除了 27 之外的所有数字都应保留为 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: unsupported operand type(s) for %=: 'list' and 'int'

非常感谢任何帮助。

最佳答案

作为替代方案,如果您愿意/能够将列表转换为 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])

关于python - 如何在数字列表上实现模数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32543901/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com