简体   繁体   English

动态一行打印2个项目

[英]Print 2 items in one line dynamically

EDIT2: (Thanks Padraic Cunningham) EDIT2 :(感谢Padraic Cunningham)

This is the error I get when I try this in the interpreter, 这是我在解释器中尝试时遇到的错误,

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

EDIT: 编辑:

Im sorry this did not solve what I was looking for, I need to do this with words, for example my output on regex looks like: 很抱歉,这并不能解决我想要的问题,我需要用单词来完成此操作,例如我在regex上的输出如下:

Tony1
7684 dogs
Garry 2
8473 dogs
sara111
0 dogs

I need it to look like: 我需要它看起来像:

Tony1 7684 dogs
Garry 2 8473 dogs
sara111 0 dogs

Is this possible? 这可能吗?

Original: 原版的:

I would like to make several statements that give standard output without seeing newlines in between statements. 我想做几个给出标准输出的语句,但不要在语句之间看到换行符。

Specifically, suppose I have: 具体来说,假设我有:

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

The output looks like: 输出如下:

1
2
3
4
.
.
.

How get this to instead look like: 如何使它看起来像:

1 2
3 4
5 6
7 8

Using print item, item + 1 will not work on all data, zip will: 使用print item, item + 1不适用于所有数据,而zip可以:

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

Or izip_longest for uneven length lists: izip_longest用于长度不均匀的列表:

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

rn[::2] gets every second element starting from elemett 0, rn[1::2] gets every second element starting from element 1 rn[::2]从elemett 0开始获取第二个元素, rn[1::2]从元素1开始获取第二个元素

From your edit, what you seem to need is to concat every two lines together: 从您的编辑中,您似乎需要将每两行连接在一起:

     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

For python 2.6: 对于python 2.6:

for it1, it2 in zip(spl[::2],spl[1::2]):
        print("{0} {1}".format(it1 ,it2))
for item in range(1,100):
if item % 2 == 0:
    print item
else:
    print item,

from the ipython shell 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]: 

It works because the list on which zip operates contains n instances of the same iterator on the argument list... 之所以有效,是因为zip操作的列表在参数列表中包含n相同迭代器的实例...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM