Python如何简化代码实现列表内容无方括号打印?
Hey there! I’ve got two super straightforward ways to fix this without complicating your code at all. Let’s break them down:
Method 1: Use str.join() with map()
Since your list contains integers, we first convert each element to a string, then join them all with ', ' as the separator. This avoids the default list string representation (which includes square brackets).
Here’s your modified code:
import random n = [random.randint(10,999) for i in range(int(input()))] print(', '.join(map(str, n)))
map(str, n)converts every integer in the listnto a string.', '.join(...)glues all those strings together with', 'between each one.
Method 2: Unpack the List with * (Even Simpler!)
Python lets you unpack list elements directly as arguments to print() using the * operator. Then you just specify the separator with the sep parameter. This is probably the shortest and cleanest solution.
Modified code:
import random n = [random.randint(10,999) for i in range(int(input()))] print(*n, sep=', ')
*ntakes every element in the list and passes them as individual arguments toprint().sep=', 'tellsprint()to put', 'between each argument instead of the default space.
Why Your Original Code Didn’t Work
When you do print(n, end=', '), you’re printing the entire list object, which Python converts to its default string format ([element1, element2, ...]). The two methods above bypass this by printing the elements directly instead of the list itself.
内容的提问来源于stack exchange,提问作者TurtleSam

