【问题标题】:How to check if a dictionary contains multiple elements?如何检查字典是否包含多个元素?
【发布时间】:2015-12-24 06:33:03
【问题描述】:

我有一个二维数组,其中每个单元格都包含一个随机填充人类、蚊子或两者的字典。这看起来像这样:

{'human': Human instance, 'mosquitoes': [Mosquito instance]}

我循环遍历二维数组,并检查每个单元格:

for row in my_array:
    for cell in row:
        if cell['human']:
            do this
        elif cell['mosquitoes']:
            do this
        elif cell[both]:
            do this

我已经尝试过here 建议的方法,但到目前为止我还无法让它工作。

【问题讨论】:

  • 您的字典中的“两者”如何显示的示例是什么?
  • 你遇到了什么错误?
  • 您可能想以某种方式“跟踪”您遇到的人数。如何存储包含多次出现的值?
  • 不确定我是否理解这个问题,您想要一种方法来测试两者(如果您在字典中有两个键)?如果是这样,elif cell['human'] and cell['mosquitoes']: 应该可以解决问题。
  • 您能否展示更多代码,以便我们更好地理解您的逻辑流程?

标签: python dictionary


【解决方案1】:

您是否考虑过尝试:

if cell['mosquitoes'] and cell['human']:
    # your code goes here for this case
elif cell['mosquitoes']:
    # your code goes here for this case
elif cell['human']:
    # your code goes here for this case

【讨论】:

  • 因为它不执行它下面的代码。它没有进入 elif。
【解决方案2】:

cell[both] 永远不会运行,因为它是最后一个 elif 检查。让它成为第一个 if。

if cell['human'] and cell['mosquitoes']:
    do this
elif cell['human']:
    do this
elif cell['mosquitoes]:
    do this

请注意,如果humanmosquitoes 键不存在,您可能会得到KeyError。因此,您可能需要使用 cell.get(key) 语法而不是 cell[key] 来应对此类事件。

【讨论】:

  • 非常感谢您提供有用的答案以及您对使用 cell.get(key) 的建议。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-16
  • 1970-01-01
  • 2017-02-27
  • 2017-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多