如何在python中打印为列表?

如何在python中打印为列表?,python,Python,我正试图将以下输出打印为如下列表 如: 1,2,3 我的代码是 import random list = 0 while list < 3: n = random.randint(1,10) print(n) list = list + 1 将其打印为逗号分隔列表的最简单方法是什么?如果你能向我解释解决方案背后的原因,那也太好了。谢谢 假设您的循环不适合用生成器表达式替换它(如注释中所示),请使用end=',' import random

我正试图将以下输出打印为如下列表 如:
1,2,3

我的代码是

import random
list = 0
while list < 3:
        n = random.randint(1,10)
        print(n)
        list = list + 1

将其打印为逗号分隔列表的最简单方法是什么?如果你能向我解释解决方案背后的原因,那也太好了。谢谢

假设您的循环不适合用生成器表达式替换它(如注释中所示),请使用
end=','

import random
list = 0
while list < 3:
        n = random.randint(1,10)
        end = ',' if list < 2 else ''
        print(n, end=end)
        list = list + 1
print()
随机导入
列表=0
当列表<3时:
n=random.randint(1,10)
结束=','如果列表<2,则为'else'
打印(n,结束=结束)
列表=列表+1
打印()

需要检测循环的最后一次迭代,改变结尾以避免后面出现逗号,这就不太理想了。

下面是注释中的代码和解释:

import random
# We create a list l to store the number
l = []

# The while loop ends when the size of l is more than 3
while len(l) < 3:
        n = random.randint(1,10)
        # Append the random number n into l
        l.append(n)
# Print the list l
print(l)
随机导入
#我们创建一个列表l来存储数字
l=[]
#当l的大小大于3时,while循环结束
而len(l)<3:
n=random.randint(1,10)
#将随机数n附加到l中
l、 附加(n)
#打印列表l
印刷品(l)

print(',').join(str(random.randint(1,10))表示范围内(3))
print(*[random.randint(1,10)表示范围内(3)],sep=',')
作为旁白,不要使用名称
list
。如果您真的只想打印列表文字,甚至不需要循环
print([random.randint(1,10)for uu in range(3)])
@chepner是的,我同意我们可以在这里使用列表理解,它会减少很多行:),但我认为这将更难解释。如果我知道OP会接受
[1,2,3],我会首先建议列表理解
作为输出,而不是
1,2,3
import random
# We create a list l to store the number
l = []

# The while loop ends when the size of l is more than 3
while len(l) < 3:
        n = random.randint(1,10)
        # Append the random number n into l
        l.append(n)
# Print the list l
print(l)