[英]Printing items in two separate lists in proper alignment using python
I am trying to print items in two separate lists in a way that items in list-1
will align with items in list-2
. 我试图以两个方式将列表中的项目打印出来,以使
list-1
项目与list-2
项目对齐。
Here is my attempt: 这是我的尝试:
import numpy as np
list_1=[1,2,3,4]
list_2=np.arange(0.1,0.4,0.1)
for x in list_1:
j=x/2.0
for y in list_2:
print j,',', y
My Output: 我的输出:
0.5 , 0.1
0.5 , 0.2
0.5 , 0.3
0.5 , 0.4
1.0 , 0.1
1.0 , 0.2
1.0 , 0.3
1.0 , 0.4
1.5 , 0.1
1.5 , 0.2
1.5 , 0.3
1.5 , 0.4
2.0 , 0.1
2.0 , 0.2
2.0 , 0.3
2.0 , 0.4
Desired Output: 所需输出:
0.5 , 0.1
1.0 , 0.2
1.5 , 0.3
2.0 , 0.4
What you want is zip()
. 您想要的是
zip()
。
Example: 例:
>>> l1 = range(10)
>>> l2 = range(20,30)
>>> for x,y in zip(l1, l2):
print x, y
0 20
1 21
2 22
3 23
4 24
5 25
6 26
7 27
8 28
9 29
Explanation: 说明:
zip
receives iterables, and then iterates over all of them at once, starting from the 0 element of each, then going on to the 1st and then 2nd and so on, once any of the iterables reaches the end - the zip will stop, you can use izip_longest
from itertools
to fill empty items in iterables with None
(or you can do some fancier things - but that is for a different question) zip
接收可迭代对象,然后一次迭代所有对象,从每个对象的0元素开始,然后依次进行第1个和第2个,依此类推,一旦任何可迭代对象到达末尾-zip将会停止,您可以使用itertools
izip_longest
来用None
填充izip_longest
空白项目(或者您可以做一些更奇特的事情-但这是另一个问题)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.