如何在一行中打印列表元素?

Hou*_*uma -2 python

我需要打印排序的整数列表,但它应该在一行中,没有列表方括号,最后没有任何'\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])
Run Code Online (Sandbox Code Playgroud)

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

FHT*_*ell 7

您可以将列表解压缩到print使用状态*,该列表将自动按空格分割

print(*l)
Run Code Online (Sandbox Code Playgroud)

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

print(*l, sep=', ')
Run Code Online (Sandbox Code Playgroud)

  • 这仅适用于 Python 3.0 及更高版本吗?这不适用于 Python 2.7 (2认同)