动态地在一行中打印2个项目

时间:2014-12-10 17:56:30

标签: python

EDIT2 :(感谢Padraic Cunningham)

这是我在解释器中尝试这个时遇到的错误,

>>> print s

Tony1
7684 dogs
Garry 2
8473 dogs
sara111
0 dogs

>>> spl = s.lstrip().splitlines()
>>> 
>>> for it1, it2 in zip(spl[::2],spl[1::2]):
...     print("{} {}".format(it1 ,it2))
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ValueError: zero length field name in format

编辑:

对不起,这并没有解决我想要的问题,我需要用文字来做,例如我在正则表达式上的输出看起来像:

Tony1
7684 dogs
Garry 2
8473 dogs
sara111
0 dogs

我需要它看起来像:

Tony1 7684 dogs
Garry 2 8473 dogs
sara111 0 dogs

这可能吗?

原件:

我想做几个语句,提供标准输出,而不会在语句之间看到换行符。

具体来说,假设我有:

for item in range(1,100):
print item

输出如下:

1
2
3
4
.
.
.

如何让它看起来像:

1 2
3 4
5 6
7 8

3 个答案:

答案 0 :(得分:2)

使用print item, item + 1不适用于所有数据,zip会:

rn  = range(1,100)
for item1,item2 in zip(rn[::2],rn[1::2]):
  print item1,item2

izip_longest不均匀长度列表:

rn = range(1,100)
for item1,item2 in izip_longest(rn[::2],rn[1::2],fillvalue=0):
  print item1,item2

rn[::2]从elemett 0开始获取每个第二个元素,rn[1::2]从元素1开始获取每个第二个元素

从您的编辑中,您似乎需要将每两行连接在一起:

     s ="""
In [1]: paste
 s ="""
Tony1
7684 dogs
Garry 2
8473 dogs
sara111
0 dogs
"""
spl = s.lstrip().splitlines()

for it1, it2 in zip(spl[::2],spl[1::2]):
    print("{} {}".format(it1 ,it2))

## -- End pasted text --
Tony1 7684 dogs
Garry 2 8473 dogs
sara111 0 dogs

对于python 2.6:

for it1, it2 in zip(spl[::2],spl[1::2]):
        print("{0} {1}".format(it1 ,it2))

答案 1 :(得分:0)

for item in range(1,100):
if item % 2 == 0:
    print item
else:
    print item,

答案 2 :(得分:0)

来自ipython shell

In [13]: def print_by(l,n):
   ....:     for t in zip(*([iter(l)]*n)):
   ....:         for el in t: print el,
   ....:         print
   ....:         

In [14]: print_by(range(40),4)
0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15
16 17 18 19
20 21 22 23
24 25 26 27
28 29 30 31
32 33 34 35
36 37 38 39

In [15]: 

它的工作原理是因为zip操作的列表包含参数列表中相同迭代器的n个实例...

相关问题