【问题标题】:Iterating through a dictionary and a list within遍历字典和列表
【发布时间】:2018-08-22 00:30:49
【问题描述】:

我有一个字典示例:

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

我要做的是通过检查每个托架(Bay1,Bay2...)来查看字典,看看哪个有一个数组,其中所有内容都是False。例如,我希望它返回'Bay4'

其次,我希望能够使用循环检查每个托架中哪个是False,哪个是True。换句话说,您可以想象True 代表“已预订”,False 代表免费或“未预订”。我希望能够检查每个托架并以良好且易于阅读的格式将其呈现给用户。

【问题讨论】:

  • 您需要向我们展示您迄今为止所做的尝试。第一个问题try this

标签: python dictionary iteration


【解决方案1】:

您应该提供更多信息。

无论如何,如果我理解您的问题,您可以在 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

【讨论】:

    【解决方案2】:

    第一部分 部分

    返回值全部为False的键:

    >>> 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-29
      • 2020-05-16
      • 1970-01-01
      相关资源
      最近更新 更多