首页 > 解决方案 > 如何在一行中打印列表元素?

问题描述

我需要打印排序后的整数列表,但它应该在一行中,没有列表方括号,最后没有任何 '\n' ...

import random
n = int(input(""))
l=[]
for i in range(n):
    x = int(input())
    l.append(x)
not_sorted = True
while not_sorted:    
    x = random.randint(0,n-1)
    y = random.randint(0,n-1)
    while x==y:
        y = random.randint(0,n-1)
    if x>y:
        if l[x]<l[y]:
            (l[x],l[y])=(l[y],l[x])
    if x<y:
        if l[x]>l[y]:
            (l[x],l[y])=(l[y],l[x])
    for i in range(0,n-1):
        if l[i]>l[i+1]:
            break
    else:
       not_sorted = False
for i in range(n):
    print(l[i])

输出应该是这样的::: 1 2 3 4 5 而不是这样 :::: [1,2,3,4,5]

标签: python

解决方案


您可以解压缩列表以print使用*它会自动按空格分隔

print(*l)

如果你想要一个逗号,使用sep=参数

print(*l, sep=', ')

推荐阅读