Python 避免在numba优化函数中使用str()
在下面的代码片段中,我希望避免在函数foo中使用Python 避免在numba优化函数中使用str(),python,numba,Python,Numba,在下面的代码片段中,我希望避免在函数foo中使用str() import numpy as np def foo(a): for runner in range(a.shape[0]): row = a[runner, :] toPrint = str(runner) + ' '+ str(row) print(toPrint) myArray = np.array(np.arange(9).reshape(3,-1)).astype(
str()
import numpy as np
def foo(a):
for runner in range(a.shape[0]):
row = a[runner, :]
toPrint = str(runner) + ' '+ str(row)
print(toPrint)
myArray = np.array(np.arange(9).reshape(3,-1)).astype('float')
foo(myArray)
输出:
0 [0. 1. 2.]
1 [3. 4. 5.]
2 [6. 7. 8.]
背景:我使用numba()时,无法在numba优化函数中使用str()
如果不允许使用
str()
,那么foo
的代码必须是什么样子?也就是说,不应该发生任何导入(因为numba在大多数情况下都不适用于它们) 考虑字符串格式:
toPrint = '{} {}'.format(runner, row)
print(toPrint)
或者简单地说(因为默认情况下有一个空格分隔参数):
如果您不想在函数foo中使用
str()
函数,为什么不先将结果附加到临时列表中,然后再打印出来呢
import numpy as np
list1 = []
def foo(a):
for runner in range(a.shape[0]):
row = a[runner, :]
toPrint = str(runner) + ' '+ str(row)
list1.append(toPrint)
myArray = np.array(np.arange(9).reshape(3,-1)).astype('float')
foo(myArray)
print(list1)
无论如何,该格式都会隐式调用
str
,因此它可能无法工作。是的,@iz_uu是正确的,很遗憾,格式无法与numba一起工作。虽然可以打印。不幸的是,print
也会调用str
或repr
中的一个。我认为简单的答案是不要在该函数中打印。您可以返回值并在调用函数中打印它吗?添加到@PaulRooney的注释中,您是在循环中打印的,因此,yield
可能会起作用,而不是return
。您可以在打印之前将其附加到列表中?如果你真的想看的话。
import numpy as np
list1 = []
def foo(a):
for runner in range(a.shape[0]):
row = a[runner, :]
toPrint = str(runner) + ' '+ str(row)
list1.append(toPrint)
myArray = np.array(np.arange(9).reshape(3,-1)).astype('float')
foo(myArray)
print(list1)