Python在循环中的一行中打印两个元素的列表

时间:2014-05-05 08:20:31

标签: python list loops

我有一个列表:

one = [(1, 2), (3, 4)]
for o in one:
    print o
(1, 2)
(3, 4)

我需要在同一行中打印(1,2)和(3,4)

for o in one:
    print o
(1, 2) (3, 4)

1 个答案:

答案 0 :(得分:4)

在python2中,它将按如下方式完成:

one = [(1, 2), (3, 4)]
for o in one:
    print o,      #added the ,
print      #and an optional print() to ensure that anything afterwords prints on a separate line

在python3中,由于print成为函数,因此需要稍作修改:

one = [(1, 2), (3, 4)]
for o in one:
    print(o, end=' ')
print()    #and an optional print() to ensure that anything afterwords prints on a separate line

或者(感谢@ user2357112的建议)

one = [(1, 2), (3, 4)]
print(*one)

[OUTPUT]  from all
(1, 2)(3, 4)