Python 使用函数,如何动态更改与变量对应的字典元素?

Python 使用函数,如何动态更改与变量对应的字典元素?,python,Python,我想将dictionary元素公式化地修改为相应的用户输入,但我不知道如何通过使用另一个参数和另一个代码块初始化元素来以通用的方式进行修改。 记住,使用字典可能不是最简单的方法 谢谢你的回答 我曾尝试在class Card下的第一个函数中添加额外的参数:但我忘记了如何通过以一种通用的公式化方式使用此参数来修改dictionary元素 class Card: def __init__(self, t, d, dd): self.title = t self.desc = d

我想将dictionary元素公式化地修改为相应的用户输入,但我不知道如何通过使用另一个参数和另一个代码块初始化元素来以通用的方式进行修改。 记住,使用字典可能不是最简单的方法

谢谢你的回答

我曾尝试在class Card下的第一个函数中添加额外的参数:但我忘记了如何通过以一种通用的公式化方式使用此参数来修改dictionary元素

class Card:
  def __init__(self, t, d, dd):
    self.title = t
    self.desc = d
    self.decision_desc = dd

  def introduce_card(self):
    print(self.title)
    print(self.desc)
    print(self.decision_desc)
    option = input("> ")
    if option.lower in ["y", "yes", "t", "true"]:
      # line to modify dictionary element corresponding to the card to true
    elif option.lower in ["n", "no", "f", "false"]
      # line to modify dictionary element corresponding to the card to false

card1 = Card("title", "desc", "yes/no")
card_ans = {"card1": False, "Card2": False, "Card3": False}

card1.introduce_card()

为了便于以后使用,我可以根据存储的布尔值进一步编程,并将其用作条件。

下面是如何使用列表进行编程:

>>> d1 = {"temp": "val"}
>>> d2 = {"temp": "val"}
>>> d3 = {"temp": "val"}
>>> list = [d1, d2, d3]
>>> list_example = [d1, d2, d3]
>>> for i, element in enumerate(list_example):
...     element["temp"] = i
...
>>> d1
{'temp': 0}
>>> d2
{'temp': 1}
>>> d3
{'temp': 2}
下面是一些基本代码,展示了如何使用输入进行操作:

>>> d1 = {"temp": "val"}
>>> d2 = {"temp": "val"}
>>> d3 = {"temp": "val"}
>>> for i, element in enumerate(list_example):
...     user_input = input("something: ")
...     element["temp"] = user_input
...
something: test1
something: test2
something: test3
>>> d1
{'temp': 'test1'}
>>> d2
{'temp': 'test2'}
>>> d3
{'temp': 'test3'}
以下是一些基本逻辑:

>>> d1 = {"temp":"val"}
>>> d2 = {"temp":"val"}
>>> d3 = {"temp":"val"}
>>> for i in list_example:
...     user_input = input("1, 2, or 3: ")
...     if user_input == "1":
...             i["temp"] = True
...     elif user_input == "2":
...             i["temp"] = False
...     else:
...             i["temp"] = "error"
...
1, 2, or 3: 1
1, 2, or 3: 2
1, 2, or 3: 3
>>> d1
{'temp': True}
>>> d2
{'temp': False}
>>> d3
{'temp': 'error'}
>>>

应该很容易修改此代码,以满足您的需要

我的10美分是为了重新审视这件衣服的设计

卡片中的键似乎基于代码中变量的名称。那么,如果变量名更改,结果会更改吗?即使您在以后阅读代码时让任何人都能使用它,这似乎是完全出乎意料的


根据我认为你可能正在做的,我的建议是考虑创建一个CARMMARTER类,它负责创建/销毁卡+管理你的回答问题。管理员将拥有函数
导入卡

对象不知道引用它们的变量的名称。对象可以从多个变量引用,甚至可以从非变量的对象引用,如列表元素。因此,对象中的方法无法找到对应于变量的dictionary元素

字典键应与
对象本身中的信息相对应,例如
标题
。那你就可以了

card_ans[self.title] = True

但是不清楚为什么你首先需要
card\u ans
字典。为什么不在
卡片
中添加
答案
属性?

我认为最好的选择是将布尔值存储为类的一部分,但假设有某种原因您不能,您可以动态引用字典,只要您有键。在这种情况下,self.title可能是关键,因此
card_ans[self.title]=True
将是一个想法。你仍然需要解决你的字典不在课堂上的问题。