Pythonic方式循环两个列表

时间:2017-11-16 10:27:58

标签: python arrays loops for-loop

我有两个数组:

Array_a = [20, 30, 50, 20]
Array_b = [1 ,2  ,3  , 4] 

希望得到以下输出:

(20, '(1,Days Learning)') 
(30, '(2,Days Learning)') 
(50, '(3,Days Learning)') 
(20, '(4,Days Learning)')

我的代码如下所示:

for i,j in zip(Array_a, Array_b):
    msg = (i, "(" + str(j) + ",Days Learning)")
    print(msg)

但是我想让它变得更容易:

for a, b in []

2 个答案:

答案 0 :(得分:4)

试试这个:

msg = [(a, '({}, Days Learning)'.format(b)) for a, b in zip(Array_a, Array_b)]
print(msg)

将输出:

[(20, '(1, Days Learning)'), (30, '(2, Days Learning)'), (50, '(3, Days Learning)'), (20, '(4, Days Learning)')]

注意:

要逐行打印元素,您可以使用printjoin以及其他列表理解:

print('\n'.join(str(m) for m in msg))

答案 1 :(得分:0)

这个怎么样: 它对我来说看起来更加蟒蛇

Array_a = [20, 30, 50, 20]
Array_b = [1 ,2  ,3  , 4] 

sample = tuple(zip(Array_a,zip(Array_b,["Days Learning" for i in range(len(Array_b))])))
print(sample)

它会给你这个结果:

((20, (1, 'Days Learning')), (30, (2, 'Days Learning')), (50, (3, 'Days Learning')), (20, (4, 'Days Learning')))