Haskell中如何输出带有换行的二维列表?
Hey there! Let's get that 2D list printing with proper newlines sorted out—your grid pattern looks like it's meant to be displayed line-by-line, so I totally get why you're frustrated with the current output.
First off, a quick note: avoid using list as a variable name—it's a built-in Python type, and redefining it can cause weird bugs later. Let's rename it to something like my_grid instead.
Here's the simplest way to print each sublist on its own line: iterate over each row, join the characters in the row into a single string, then print that string. Python's print() function automatically adds a newline at the end of each call, so this will give you the clean, grid-like output you want.
# Your grid (renamed to avoid overriding built-in list) my_grid = [ [' ',' ','*',' ',' ',' ',' ',' ',' ','*',' ',' ',' ',' ',' ',' ','*',' ',' '], [' ','*',' ','*',' ',' ',' ',' ','*',' ','*',' ',' ',' ',' ','*',' ','*',' '], ['*',' ','*',' ','*',' ',' ','*',' ','*',' ','*',' ',' ','*',' ','*',' ','*'], ['-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-'], [' ',' ','1',' ',' ',' ',' ',' ',' ','2',' ',' ',' ',' ',' ',' ','3',' ',' '] ] # Print each row as a single line for row in my_grid: print(''.join(row))
If you prefer to output everything in one go instead of looping, you can combine all rows into a single string separated by newlines:
print('\n'.join(''.join(row) for row in my_grid))
The reason your previous attempts might have failed is that printing the list directly (like print(my_grid)) will show Python's raw list representation, which doesn't handle line breaks or character formatting for display. By joining each row into a string first, you're telling Python exactly how you want each line to look.
内容的提问来源于stack exchange,提问作者Harpreet SINGH

