【问题标题】:Python print a list of two element in one line in a loop [duplicate]Python在循环中的一行中打印两个元素的列表[重复]
【发布时间】:2014-06-21 11:40:00
【问题描述】:

我有一个列表:

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)

【问题讨论】:

  • print o, 会这样做
  • 不是完全重复,但它有解决这个问题的方法。
  • @thefourtheye 我认为足够好。无论如何,谷歌搜索 3 秒即可找到答案

标签: python list loops


【解决方案1】:

在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)

【讨论】:

  • Python 3 示例不起作用,因为删除了令人困惑的软空间功能。查看输出,缺少空格:ideone.com/S5bErt
  • @user2357112,你的意思是中间没有空格吗?
  • 是的。我推荐print(*one),没有循环。
  • @user2357112,非常感谢。我已将其包含在我的答案中。
  • 另外,print o,print(o, end='') 版本可能需要在末尾额外添加一个 print 才能获得换行符,因此您要打印的下一个内容不会显示在同一位置也行。
猜你喜欢
  • 2022-01-23
  • 1970-01-01
  • 1970-01-01
  • 2019-02-03
  • 2019-09-05
  • 1970-01-01
  • 1970-01-01
  • 2012-10-11
  • 2018-04-02
相关资源
最近更新 更多