You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中创建自定义填充、指定宽高的Array2d

如何在Python中创建指定宽高、自定义字符串值的二维数组

方法1:列表推导式(推荐)

这是Python中最简洁高效的实现方式,能生成完全独立的行,避免引用关联问题:

# 定义参数
height = 3  # 行数
width = 4   # 列数
custom_str = "my_custom_string"

# 生成二维数组
array_2d = [[custom_str for _ in range(width)] for _ in range(height)]

运行后输出:

print(array_2d)
# 结果:
# [['my_custom_string', 'my_custom_string', 'my_custom_string', 'my_custom_string'],
#  ['my_custom_string', 'my_custom_string', 'my_custom_string', 'my_custom_string'],
#  ['my_custom_string', 'my_custom_string', 'my_custom_string', 'my_custom_string']]

方法2:嵌套循环(适合新手理解)

如果想直观看到二维数组的构建过程,可以用嵌套循环逐行生成:

height = 3
width = 4
custom_str = "test_string"

array_2d = []
for _ in range(height):
    # 初始化单行
    current_row = []
    for _ in range(width):
        current_row.append(custom_str)
    # 将单行加入二维数组
    array_2d.append(current_row)

需要避免的错误写法

不要使用[[custom_str] * width] * height的方式,这种写法会让所有行指向同一个列表引用,修改任意一行的元素会同步影响所有行:

# 错误示例
bad_array = [[custom_str] * width] * height
bad_array[0][0] = "modified"
print(bad_array)
# 所有行的第一个元素都被修改:
# [['modified', 'test_string', 'test_string', 'test_string'],
#  ['modified', 'test_string', 'test_string', 'test_string'],
#  ['modified', 'test_string', 'test_string', 'test_string']]

内容的提问来源于stack exchange,提问作者dns51

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 21:43:08