简体   繁体   中英

How to print in one line the outputs of two lists?

I have two lists A: contains number from 1 to 10, and B contains percentage values. I'd like to print them in this way

1: 10%, 2: 40%, 3: 50%

I managed to write only one array but I can't find a way to write both of them.

print(' : '.join(str(x) for x in A))

I tested zip but it printed only the first value of A and the rest of B

print(''.join(str(x) + " : " + str(y) for x, y in zip(A, B)))

0 : 2821 : 3422 : 2963 : 3024 : 3155 : 2496 : 3067 : 3198 : 2729 : 317

Any idea how to implement it without using for loop ?

spam = [1, 2, 3]
eggs = [10, 20, 30]
print(', '.join(f'{n}:{prct}%' for n, prct in zip(spam, eggs)))

if the first list has just numbers it can be even just

eggs = [10, 20, 30]
print(', '.join(f'{n}:{prct}%' for n, prct in enumerate(eggs, start=1)))

Would something like this work for you?

A = range(1, 11)
B = [10, 40, 50, 30, 70, 20, 45, 80, 20, 35]

print(', '.join(['{}: {}%'.format(n, p) for n, p in zip(A, B)]))

# 1: 10%, 2: 40%, 3: 50%, 4: 30%, 5: 70%, 6: 20%, 7: 45%, 8: 80%, 9: 20%, 10: 35%

you can just do it like:

idx = [1, 2, 3]
percent = [10,40,50]

print(', '.join(f'{idx[i]}:{percent[i]}%' for i in range(len(idx))))

output:

1:10%, 2:40%, 3:50%

you can use a for loop:

a = [1, 2, 3]
b = [0.1, 0.2, 0.3] # percentage values

for i, j in zip(a, b):
    print(f'{i}:{j:.0%}', end =', ')

output:

1:10%, 2:20%, 3:30%,

You were doing correctly with the help of zip , Try the below code where I have made little changes in your code:-

a = [1,2,3]
b = [10,40,50]
print(', '.join(str(x) + " : " + str(y)+'%' for x, y in zip(a, b)))

Output

1 : 10%, 2 : 40%, 3 : 50%

Let, a=[1,2,3] b=[4,5,6] print(*a,*b)

I hope it helps.

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