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

如何在Python行列输出代码中添加动态Row #x:前缀?

如何给Python矩阵每行添加动态行号前缀?

我是一名大学新生,Python是我的第一门编程语言。我编写了一段输入行列数并输出连续数字矩阵的代码:

x = int(input("Enter the number of rows: "))
y = int(input("Enter the number of columns: "))

n=1
for i in range(x):
    for j in range(y):
        print(n, end=" ")
        n = n+1
    print()

当前输出示例:

Enter the number of rows: 3
Enter the number of columns: 3
1 2 3
4 5 6
7 8 9

我希望在每行开头添加动态的"Row #x:"前缀(x为对应行号),预期输出如下:

Enter the number of rows: 3
Enter the number of columns: 3
Row #1: 1 2 3
Row #2: 4 5 6
Row #3: 7 8 9

解决方案

你只需要在外层循环的开头,先打印带行号的前缀即可。因为range(x)生成的是从0开始的序列,所以行号需要用i+1来表示:

修改后的代码如下:

x = int(input("Enter the number of rows: "))
y = int(input("Enter the number of columns: "))

n = 1
for i in range(x):
    # 先打印行号前缀,end=""避免换行
    print(f"Row #{i+1}: ", end="")
    for j in range(y):
        print(n, end=" ")
        n += 1
    print()

这样运行后就能得到你想要的输出。另外也可以用字符串格式化的其他方式,比如"Row #{}: ".format(i+1),效果是一样的,f-string是Python 3.6+的语法,更简洁直观。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 19:00:58