1

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 ?

Feras
  • 834
  • 7
  • 18

6 Answers6

3
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)))
buran
  • 13,682
  • 10
  • 36
  • 61
  • The op stated "zip didn't work", so until we know what he meant by "didn't work", telling him to use "zip" is not going to help... – bruno desthuilliers Sep 02 '19 at 13:04
  • 4
    @brunodesthuilliers, well, it's clear "didn't work" is "i didn't know how to use it right", as evident from his now edited question.... – buran Sep 02 '19 at 13:06
  • 2
    @buran exactly you are right. I think bruno desthuilliers should calm down a little. – Feras Sep 02 '19 at 13:07
0

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%

dms
  • 1,260
  • 7
  • 12
0

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%
ncica
  • 7,015
  • 1
  • 15
  • 37
0

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%,
kederrac
  • 16,819
  • 6
  • 32
  • 55
0

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%
Rahul charan
  • 765
  • 7
  • 15
-1

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

I hope it helps.

Akshay Nailwal
  • 196
  • 1
  • 9