[英]Print 2 items in one line dynamically
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
編輯:
很抱歉,這並不能解決我想要的問題,我需要用單詞來完成此操作,例如我在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
使用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))
for item in range(1,100):
if item % 2 == 0:
print item
else:
print item,
從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
相同迭代器的實例...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.