简体   繁体   中英

Print 2 items in one line dynamically

EDIT2: (Thanks 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:

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:

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

Or izip_longest for uneven length lists:

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

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:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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