我将使用以下语句计算每个嵌套字典的值:{k: sum(1 for val in v.itervalues() if val == 'available') for k, v in seats.iteritems()}
这将从与seats相同的键构建一个新字典,每个值都是可用的座位数。使用生成器技巧的sum(..)可以有效地计算每行字典中包含的值等于'available'的所有值。在
结果:
^{pr2}$
要显示特定行的可用座位,请过滤并使用len():row_available = [k for k, v in seats[rowChoice].iteritems() if v == 'available']
avail_count = len(row_available)
if avail_count:
print 'there {is_are} {count} seat{plural} available in row {rowChoice}, seat{plural} {seats}'.format(
is_are='are' if avail_count > 1 else 'is', count=avail_count,
plural='s' if avail_count > 1 else '', rowChoice=rowChoice,
seats=row_available[0] if avail_count == 1 else ' and '.join([', '.join(row_available[:-1]), row_available[-1]]))
对于rowChoice = 'A'此打印:there are 2 seats available in row A, seats A1 and A3
但它也会调整以形成连贯的句子,以适应更多或更少的座位。在