简体   繁体   English

如何在一行中打印两个列表的输出?

[英]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. 我有两个列表A:包含1到10的数字,B包含百分比值。 I'd like to print them in this way 我想用这种方式打印

1: 10%, 2: 40%, 3: 50% 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 我测试了zip,但只打印了A的第一个值和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 0:2821:3422:2963:3024:3155:2496:3067:3198:2729:317

Any idea how to implement it without using for loop ? 任何想法如何不使用for循环来实现它?

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: 您可以使用for循环:

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:- 您在zip的帮助下做得正确,请尝试以下代码,在我对您的代码所做的改动很小的地方:

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) 设a = [1,2,3] b = [4,5,6] print(* a,* b)

I hope it helps. 希望对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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