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

Python乘法表代码输出格式异常:需转为扁平化输出求助

Fixing Your Multiplication Table Output Format

Got it, let's break down why your current code is outputting a nested list instead of the space-separated string you want, and fix it up.

The Problem with Your Current Code

Right now, you're creating a new single-element list temp for every product, then appending that small list to table. That's why table ends up as [[1], [2], [2], [4]]—a list of lists. When you print this directly, Python just shows the raw nested list structure, which isn't what you're after.

Solution 1: Build a Flat List and Join It

The cleanest way to get your desired output is to store all products in a single flat list (no nested sublists), then convert that list into a space-separated string. Here's the modified code:

row_one = int(input("Enter row number:"))
column = int(input("Enter column number:"))
table = []
for j in range(1, row_one + 1):
    for i in range(1, column + 1):
        table.append(j * i)  # Add the product directly, not wrapped in a sublist
# Convert numbers to strings and join with spaces
print(' '.join(str(num) for num in table))

When you input 2 for rows and 2 for columns, this will output exactly what you want: 1 2 2 4.

Solution 2: Print Directly Without Storing (Simpler for One-Time Output)

If you don't need to keep the products stored in a list afterward, you can print each product as you calculate it, using end=' ' to keep everything on the same line. We'll add a final print to move the cursor to a new line:

row_one = int(input("Enter row number:"))
column = int(input("Enter column number:"))
for j in range(1, row_one + 1):
    for i in range(1, column + 1):
        print(j * i, end=' ')
# Add a newline at the end
print()

Note: This will leave a trailing space at the end of the line. If that's a problem, stick with Solution 1—it avoids that issue entirely.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:12:56