简体   繁体   中英

print 2 list items on the same line

I have two lists:

a=[1, 2, 3, 4, 5]
b=[6, 7, 8, 9, 10]

I need to print the first 3 items of the list on the same line. The output should look like this:

1 6
2 7
3 8

I have tried this code but it just prints everything in a row:

for i in range(len(a)):
    print(a[i])
for j in range(len(b)):
    print(b[j])

Use zip if the lists are always the same size

for x in zip(a, b):
    print(*x)

Or itertools.zip_longest if not

for x in itertools.zip_longest(a, b):
    print(*x)

Output

1 6
2 7
3 8
4 9
5 10

Note that in case of unequal lists the shorter list will pad None . You can replace it with other default value with fillvalue parameter

itertools.zip_longest(a, b, fillvalue=default_value)

If length is fixed and you only want the first three from each list:

a=[1, 2, 3, 4, 5]
b=[6, 7, 8, 9, 10]

for i in range(3):
   print("{} {}".format(a[i], b[i]))

Outputs:

1 6
2 7
3 8

If you want all the items, but lists can be different length:

a=[1, 2, 3, 4, 5, 6, 7, 8]
b=[6, 7, 8, 9, 10]

for i in range( min(len(a), len(b)) ):
   print("{} {}".format(a[i], b[i]))

Outputs:

1 6
2 7
3 8
4 9
5 10

Perhaps this

for i in zip(a,b):
    print(*i)

This will also allow for lists to be of different lengths

This prints the output you are looking for:

for i in range(3):
    print(a[i],b[i])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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