【发布时间】: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