NumPy数组中每个字符串的长度 [英] Length of each string in a NumPy array
本文介绍了NumPy数组中每个字符串的长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
NumPy中是否有任何内置操作可以返回数组中每个字符串的长度?
Is there any builtin operation in NumPy that returns the length of each string in an array?
我不认为任何 NumPy字符串操作可以吗?
我可以使用for
循环来完成此操作,但是也许还有一些更有效的方法?
I can do it with a for
loop, but maybe there's something more efficient?
import numpy as np
arr = np.array(['Hello', 'foo', 'and', 'whatsoever'], dtype='S256')
sizes = []
for i in arr:
sizes.append(len(i))
print(sizes)
[5, 3, 3, 10]
推荐答案
您可以使用numpy
中的vectorize
.它要快得多.
You can use vectorize
of numpy
. It is much faster.
mylen = np.vectorize(len)
print mylen(arr)
这篇关于NumPy数组中每个字符串的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文