numpy object_ array を使用して可変長文字列を格納しています。
a = np.array(['hello','world','!'],dtype=np.object_)
すべての要素をループせずに、配列内の最も長い文字列の長さを見つける簡単な方法はありますか?
max(a, key=len)
len(max(a, key=len))
明示的なループをコーディングする必要なく、最長の文字列 (およびその長さ) を提供しますmax
。
文字列を dtype オブジェクトの numpy 配列に格納すると、ループせずにオブジェクト (文字列) のサイズを取得できません。ただし、np.array に dtype を決定させる場合は、dtype を覗いて最長の文字列の長さを調べることができます。
In [64]: a = np.array(['hello','world','!','Oooh gaaah booo gaah?'])
In [65]: a.dtype
Out[65]: dtype('|S21')
In [72]: a.dtype.itemsize
Out[72]: 21
2 番目の列で最も長い文字列を取得したいとします。
data_array = [['BFNN' 'Forested bog without permafrost or patterning, no internal lawns']
['BONS' 'Nonpatterned, open, shrub-dominated bog']]
def get_max_len_column_value(data_array, column):
return len(max(data_array[:,[column]], key=len)[0])
get_max_len_column_value(data_array, 1)
>>>64