【问题标题】:Python INI File How to Separate Contents of 1 Variable into 3 Separate VariablesPython INI 文件如何将 1 个变量的内容分成 3 个单独的变量
【发布时间】:2017-08-04 17:21:05
【问题描述】:

我正在开发一个从 INI 文件中读取以配置一些屏幕按钮的 GUI。我被困在试图分离从 INI 文件返回的一些数据。基本上我有一个按钮“类型”,它是 4 个选项中的 1 个,根据类型,GUI 将为按钮分配一个功能。 (我正在使用 INI 文件,以便将来轻松更改按钮功能)

我要做的是将按钮分类为类型组,然后将该组中的哪些按钮识别到它们自己的变量中。

这里是按钮类型的 INI 文件:

[Button1]
type = Run Mission

[Button2]
type = Set Register

[Button3]
type = Set Register

[Button4]
type = Set Register

[Button5]
type = Indicator

[Button6]
type = Set Register

[Button7]
type = Data

[Button8]
type = Data

[Button9]
type = Data

这是我试图用来提取这些数据的代码。我正在使用 configparser 来读取 INI 文件。问题是当我print k 测试传入的数据时,它会打印type_7, type_9, type_8,如果可能的话;我需要将它们分别放在自己的变量中或以某种方式分开。我没有包含所有 GUI 代码以保持帖子简短,但如果需要更多代码,请告诉我。我是 python 新手,看过很多类似的帖子,但似乎找不到具体的方法。

type_dict = {}

    type_dict['type_1'] = config.get("Button1", "type")
    type_dict['type_2'] = config.get("Button2", "type")
    type_dict['type_3'] = config.get("Button3", "type")
    type_dict['type_4'] = config.get("Button4", "type")
    type_dict['type_5'] = config.get("Button5", "type")
    type_dict['type_6'] = config.get("Button6", "type")
    type_dict['type_7'] = config.get("Button7", "type")
    type_dict['type_8'] = config.get("Button8", "type")
    type_dict['type_9'] = config.get("Button9", "type")

    print type_dict

    """for k, v in type_dict.items():
        if v == "Run Mission":
            print k

    for k, v in type_dict.items():
        if v == "Set Register":
            print k

    for k, v in type_dict.items():
        if v == "Indicator":
            print k"""

    for k, v in type_dict.items():
        if v == "Data":
            print k

非常感谢任何帮助。提前谢谢!

【问题讨论】:

  • 否决票的解释?
  • 好吧,例如最后一个 for 循环我从字典中返回多个键,因为多个键符合 v == "Data" 的条件。我试图在自己的变量中返回它们。这样做的目的是让我的代码不依赖于知道每种类型有多少,因为每种类型的数量可以是动态的。

标签: python user-interface dictionary ini


【解决方案1】:

这将为您提供一个以“数据”为值的键列表。这能满足您的需要吗?

data_buttons = [k for k, v in type_dict.items() if v == "Data"]

【讨论】:

  • 是的,这让它们进入了一个列表,然后我可以像我想的那样解析成单个变量。谢谢你的建议!
猜你喜欢
  • 1970-01-01
  • 2020-02-08
  • 1970-01-01
  • 2020-07-30
  • 1970-01-01
  • 2017-02-15
  • 2012-03-30
  • 1970-01-01
  • 2018-04-10
相关资源
最近更新 更多