
NumPy 中直接使用 dtype=str 会默认创建长度为 1 的 Unicode 字符串数组,导致赋值时被截断;需显式指定足够大的固定长度(如
numpy 中直接使用 `dtype=str` 会默认创建长度为 1 的 unicode 字符串数组,导致赋值时被截断;需显式指定足够大的固定长度(如 ` 在 NumPy 中声明字符串数组时,一个常见误区是直接使用 dtype=str。例如: 输出结果中 'ddd' 被截断为 'd',这是因为 dtype=str 实际等价于 dtype=' ✅ 正确做法有两种: 方法一:指定足够大的固定长度(推荐用于同构字符串场景) ⚠️ 注意事项: 总结:永远不要依赖 dtype=str 声明可变长字符串数组——明确指定 import numpy as np
row_length = 5
col_length = 3
x = np.empty([row_length, col_length], dtype=str)
x[1, 2] = 'ddd'
print(x)
使用显式的 Unicode 字符串类型,如 x = np.empty([row_length, col_length], dtype='<u10 x print><blockquote><p>? 类型说明:'<u unicode></u></p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/ai/4139" title="Trancy"><img
src="https://img.php.cn/upload/ai_manual/001/246/273/178599608429521.png" alt="Trancy" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/ai/4139" title="Trancy" class="overflowclass">Trancy</a>
<p class="overflowclass">Trancy是一款AI学习资源工具,AI驱动的语言学习工具。</p>
</div>
<a rel="nofollow" href="/ai/4139" title="Trancy" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div></blockquote>
<p><strong>方法二:使用 dtype=object(适用于长度差异大或含复杂对象)</strong><br>
该类型不限制字符串长度,但牺牲向量化性能与内存连续性:</p>
<pre class="brush:php;toolbar:false;">x = np.empty([row_length, col_length], dtype=object)
x[1, 2] = 'ddd'
x[2, 1] = 'a very long string indeed'
print(repr(x[2, 1])) # 完整输出,无截断










