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

Python如何简化代码实现列表内容无方括号打印?

Solution to Remove Square Brackets from List Output

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 list n to 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=', ')
  • *n takes every element in the list and passes them as individual arguments to print().
  • sep=', ' tells print() 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 17:07:43