python - 如何向量化这个?

标签 python numpy

我正在寻找矢量化的方法:

for x in range(1,N+1):
  mul3ou5 = "inf"*(x%3 == 0)+"luans"*(x%5==0) 
  print str(x)*(mul3ou5 =="")+mul3ou5

这个想法是使用 numpy 数组并通过对 numpy 数组进行一次操作来替换 for 循环numpy.array(range(100))

提前致谢

最佳答案

虽然@morningsun的答案很好,但另一个选择是这样的(使用 boolean indexing ):

import numpy as np

x = np.arange(1, N+1)
s = x.astype('S8')
s[x % 3 == 0] = 'inf'
s[x % 5 == 0] = 'luans'
s[x % 15 == 0] = 'influans'

我发现它更直观,因为它保留了显式模数 (%) 运算。

关于python - 如何向量化这个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33799879/

相关文章:

python - 为什么 sklearn 和 numpy 不同意 PCA 的乘法分量?

python - "Merging"具有共同维度的 numpy 数组

python - 选择特定用户

python - 使用 python urllib2 获取位置 header 的值

Python 程序在 shell 中工作,但从 IDLE 运行时不工作

python - 逻辑与嵌套 bool 数组

python - 切片分配的 Numpy 切片意外失败

python - 使用 BeautifulSoup 获取标签内的所有内容

python - 关于内存使用和for循环的简单Python问题

python - 在特定时间间隔内找到列表最大值的最快方法