Python 在一行中动态打印2项
编辑2:(谢谢帕德雷克·坎宁安) 这是我在解释器中尝试时遇到的错误Python 在一行中动态打印2项,python,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
>>> 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
1 2
3 4
5 6
7 8
这可能吗
原件:
我想做几个语句,这些语句提供标准输出,而不会在语句之间看到换行符
具体来说,假设我有:
for item in range(1,100):
print item
输出如下所示:
Tony1
7684 dogs
Garry 2
8473 dogs
sara111
0 dogs
1
2
3
4
.
.
.
如何使其看起来像:
Tony1 7684 dogs
Garry 2 8473 dogs
sara111 0 dogs
1 2
3 4
5 6
7 8
使用
打印项目,项目+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))
从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
实例…第二行Garry 2 8473 dogs
上为什么有四个项目可能重复?这是我从脚本得到的输出,“Garry 2”在一行,“8473 dogs”在下一行我看到的唯一逻辑是你想把每两行连接在一起非常感谢到目前为止,但我在尝试这个时遇到了一个错误。。回溯(最近一次调用):文件“”,第2行,在ValueError中:格式为零长度字段名打印spl时,它看起来像什么?