如何在python中打印为列表?

2024-06-02 05:08:33 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我的代码是

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

但是我的输出是这样的

1
2
3

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


Tags: 方法代码import列表原因random解决方案list
2条回答

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

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)

假设您的循环不适合用生成器表达式替换它(如注释中所示),请使用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()

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

相关问题 更多 >