【问题标题】:Is it Possible to Iterate over Multiple Dict Keys at Once?是否可以一次迭代多个字典键?
【发布时间】:2019-12-05 04:28:08
【问题描述】:

我正在为一个在线 MOOC 研究一个问题,我正在研究编写一个函数,该函数获取药物列表并查看病毒列表中的哪种病毒对所有药物都有抗药性。

我已经使用标志解决了它,但我正在尝试寻找其他方法来解决它。 我想到的一种方法是,如果可能的话,一次使用药物列表并作为键并将值作为列表作为回报,这显然行不通(我在搜索后发现我不能使用列表作为字典键)。 所以我的问题是:是否可以使用可迭代作为字典键,其中可迭代的每个元素都是字典的单独键?

我尝试过使用列表,但没有成功,但我知道元组可以作为字典键,但前提是元组本身是一个不同的键,而不是它的元素。

这是我想到的功能:

def getResistPop(self, drugResist):
        """
        Get the population of virus particles resistant to the drugs listed in
        drugResist.       

        drugResist: Which drug resistances to include in the population (a list
        of strings - e.g. ['guttagonol'] or ['guttagonol', 'srinol'])

        returns: The population of viruses (an integer) with resistances to all
        drugs in the drugResist list.
        """

        totalPop = 0
        for v in self.viruses:
            if all(v.resistances[drugResist]):
                totalPop += 1

这是我最好的不使用标志。 但当然它不起作用,给出一个列表不能用作字典键的错误。 我想知道类似的事情是否可能。 谢谢!

编辑:根据@Yongkang Zhao 的要求,这里是一些示例数据:

测试运行有以下信息:

virus1 = ResistantVirus(1.0, 0.0, {"drug1": True}, 0.0)
virus2 = ResistantVirus(1.0, 0.0, {"drug1": False, "drug2": True}, 0.0)
virus3 = ResistantVirus(1.0, 0.0, {"drug1": True, "drug2": True}, 0.0)
patient = sm.TreatedPatient([virus1, virus2, virus3], 100)
patient.getResistPop(['drug1']): 2
patient.getResistPop(['drug2']): 2
patient.getResistPop(['drug1','drug2']): 1
patient.getResistPop(['drug3']): 0
patient.getResistPop(['drug1', 'drug3']): 0
patient.getResistPop(['drug1','drug2', 'drug3']): 0

每行调用getResistPop后的数字是预期的抵抗所有给药药物的病毒数。

【问题讨论】:

  • 你能发布一些示例数据吗?
  • 发布drugResist 内容和预期结果
  • self.viruses[virus].resistances 数据结构是什么?字典?
  • "是否可以使用可迭代对象作为字典键..." - 是的:{'ab': 5}['ab'],其中'ab' 是可迭代对象; “......那个迭代的每个元素都是字典的一个单独的键?” - 是的:{'a': 5, 'b': 6, 'ab': 30}['ab']。这是你想问的吗?我认为您的问题是是否可以在某些可迭代的情况下为每个 k 检索索引 k 处的字典元素,不是吗?
  • @YongkangZhao 添加了更多数据。感谢您指出。

标签: python dictionary tuples iteration


【解决方案1】:

您建议的功能很接近,您只是没有正确使用all()

def getResistPop(self, drugResist):
    """<trimmed>"""

    totalPop = 0
    for v in self.viruses:
        if all(x in v.resistances for x in drugResist):
            totalPop += 1

澄清一下 - 在这种情况下,您并没有真正地一次迭代多个 dict 键,而是检查您的所有药物是否都在病毒的抗药性集中,每个病毒。

【讨论】:

  • 谢谢!您的答案与我正在寻找的答案非常接近,但它给了我想要的洞察力。我对其进行了轻微修改,现在它就像一个魅力! :D 这是我制作的:def getResistPop(self, drugResist): """&lt;trimmed&gt;""" totalPop = 0 for v in self.viruses: if all(d in v.resistances and v.resistances[d] for d in drugResist): totalPop += 1 return totalPop
  • @MahmoudAbdel-Mon'em 好电话,我忘了你的 dict 值是布尔值。很高兴它有帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-12-06
  • 1970-01-01
  • 2016-09-01
  • 2020-12-27
  • 2010-11-20
  • 2021-06-08
相关资源
最近更新 更多