Python乘法表代码输出格式异常:需转为扁平化输出求助
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

