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

2024-05-17 00:05:29 发布

您现在位置:Python中文网/ 问答频道 /正文

编辑2:(谢谢帕德雷克·坎宁安)

这是我在解释器中尝试的错误

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

编辑:

很抱歉,这没有解决我要找的问题,我需要用单词来解决,例如,我在regex上的输出如下所示:

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

Tags: informat编辑for语句itemspl解释器
3条回答
for item in range(1,100):
if item % 2 == 0:
    print item
else:
    print item,

使用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]获取从元素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))

ipythonshell

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实例。。。你知道吗

相关问题 更多 >