简体   繁体   English

使用python以正确对齐方式在两个单独的列表中打印项目

[英]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.

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