python - 将 python 列表增加 mod x_i 的量,其中 x_i 取决于位置

标签 python python-3.x numpy modulo

我有两个长度相等的列表。 我将 list1 增加一定量,但每个条目都必须由 list2 中的相应条目进行修改。

我正在做的是:

for ii in range(len(list1)):
    list1[ii] = (list1[ii]+val) % list2[ii]

有更好的方法(也许使用 numpy)吗?我找不到任何。这些列表非常长,因此性能是一个问题。

最佳答案

您可以使用enumeratezip减少涉及的索引量:

for ii, (a, b) in enumerate(zip(list1, list2)):
    list1[ii] = (a + val) % b

也就是说,您最好只使用列表理解来完全避免对索引的需要,因此您可以删除 enumerate 并仅使用 zip,这使得代码看起来更干净(并且代码启动更快):

# Creates a new list and rebinds list1 to it:
list1 = [(a + val) % b for a, b in zip(list1, list2)]

# Or if list1 *must* be modified in place, slice assignment can do that:
list1[:] = [(a + val) % b for a, b in zip(list1, list2)]

请注意,在这两个示例中,我将 list 重命名为 list1,因为遮蔽 list 构造函数的名称​​很糟糕 想法。

关于python - 将 python 列表增加 mod x_i 的量,其中 x_i 取决于位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54612684/

相关文章:

python-3.x - 在 AWS Lambda 中安装 Python 包?

python - 复制二维 numpy 数组中的边界

python - 带向量参数的 Numpy 数组广播

python - Linux 中的 Century Gothic 字体

python - 如何在 Python 中创建一个通用方法来执行多个管道 shell 命令?

django - 运行PyCharm测试时,如何解决“django.core.exceptions.ImproperlyConfigured:找不到GDAL库”?

python - VSCode + Pytest : "Error: TypeError: Cannot read property ' $' of undefined"

python - 二维 numpy 数组的切片、索引和迭代

python - 如何矢量化我的代码并获取所有唯一对

python - 如何计算 tfidf 矩阵中用 kmeans 解释的方差?