遍历字典和列表

2024-10-01 00:19:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字典的例子:

dictionary = {Bay1: [False,False,True],
        Bay2: [True,True,True],
        Bay3: [True,True,False],
        Bay4: [False,False,False] }

我要做的是通过检查每个间隔(Bay1,Bay2…)来浏览字典,看看哪个有一个数组,其中所有内容都是False。对于这个例子,我希望它返回'Bay4'

其次,我希望能够通过使用循环检查每个间隔中的FalseTrue。换句话说,您可以想象True表示“预订”,而False表示免费或“未预订”。我希望能够检查,为每个海湾,并提出了一个良好的,易于阅读的格式给用户


Tags: 用户falsetrue内容间隔dictionary字典格式
2条回答

第一部分

返回值为allFalse的键:

>>> d = {'Bay1': [False,False,True],
     'Bay2': [True,True,True],
     'Bay3': [True,True,False],
     'Bay4': [False,False,False]}

>>> ' '.join([k for k, v in d.items() if any(v) is False])
Bay4

第二部分

每个bayTrue(已预订)和False(未预订)计数数:

>>> d = {'Bay1': [False,False,True],
         'Bay2': [True,True,True],
         'Bay3': [True,True,False],
         'Bay4': [False,False,False]}

>>> '\n'.join(['{}: {} booked and {} not booked'.format(k, v.count(True), v.count(False)) for k, v in d.items()])
Bay1: 1 booked and 2 not booked                                
Bay2: 3 booked and 0 not booked                             
Bay3: 2 booked and 1 not booked                             
Bay4: 0 booked and 3 not booked

你应该提供更多的信息

无论如何,如果我理解了您的问题,您可以在for循环中使用any()all()

# print all Bay with all False:
for key, value in mydict:
    if not any(value):
        print key

# print all Bay with at least 1 False:
for key, value in mydict:
    if not all(value):
        print key

相关问题 更多 >