如何压缩两个数组而不截断到最短的数组?

时间:2016-05-07 14:57:46

标签: python arrays

我试图在python中编写一个脚本,它给出了数组A中的每个项目以及它在数组B中对应的内容

假设阵列A是客户 和阵列B是房间

A = 'Customer 1','Customer 2','Customer 3','Customer 4'
B = 'room 1','room 2','room 3','room 4'

for Customers,rooms in zip(A,B):
    print Customers +' is in '+ rooms

,输出为:

Customer 1 is in room 1
Customer 2 is in room 2
Customer 3 is in room 3
Customer 4 is in room 4

现在如果我们在阵列B中只有3个房间怎么办? 输出很好地忽略了客户4

Customer 1 is in room 1   
Customer 2 is in room 2
Customer 3 is in room 3

如果A> b

,我的问题是如何让它为我写all rooms are reserved
Customer 1 is in room 1
Customer 2 is in room 2
Customer 3 is in room 3
customer 4 all rooms are reserved

2 个答案:

答案 0 :(得分:3)

您可以使用itertools.izip_longest而不是zip来填充包含None值的较短列表,并更新您的逻辑,如下所示:

from itertools import izip_longest

for customer, room in izip_longest(A, B):
    if room:
        print customer + ' is in ' + room
    else:
        print customer + ' all rooms are reserved'

答案 1 :(得分:2)

我不是100%我理解你的意思

  

如果A> b

,如何让它为我写的所有房间都被保留

但我的推论是,如果你是A> B,你想要某种默认值。为此,您可以使用itertools.zip_longest

from itertools import zip_longest

A = 'Customer 1','Customer 2','Customer 3','Customer 4'
B = 'room 1','room 2','room 3','room 4', 'room 5', 'room 6'

for Customer, rooms in zip_longest(A, B, fillvalue='all rooms reserved'):
    print(Customer, rooms)

如果您只需要在A> B时显示all rooms reserved,那么您只需要if语句并打印...但这太简单了。