【问题标题】:Python: Save keywords in a list and add another list to the single words in it [closed]Python:将关键字保存在列表中并将另一个列表添加到其中的单个单词中[关闭]
【发布时间】:2016-10-08 09:20:09
【问题描述】:

我想要一个全局变量。在变量中,我想保存一个关键字列表。在我想向每个关键字添加另一个布尔值列表之后。我的第一次尝试是这样做:

global variable = {}
for word in wordlist:
    variable[word]
    for boolean in booleanlist:
        variable[word].append(True)

由于 KeyError,我在“variable[word]”处收到错误。这应该是我将单词添加到列表中的部分。 因此,在我想计算每个单词的所有 Trues 之后,例如:

variable[wordA].count(True)

感谢您的帮助:)

【问题讨论】:

  • 为什么/你(不)问什么?
  • 我不明白'variable[word]'这一行。你想做什么 ?这里没有赋值,没有副作用。
  • @TimF 我试图在列表中添加这个词。但这对我不起作用...
  • @LogicStuff 忘了说我在“variable[word]”中出现错误,我想将这个词添加到列表中。

标签: python


【解决方案1】:

无法准确确定您需要什么,但它看起来像布尔列表的字典

wordlist = ["toto", "tata", "tutu"]
booleanlist = [True, False]

variable = {word: booleanlist for word in wordlist}

给你:

{'toto': [True, False], 'tutu': [True, False], 'tata': [True, False]}

variable['tutu'].count(True)

1

希望对这里有所帮助, 干杯

【讨论】:

    【解决方案2】:

    要修复 KeyError,您可以执行以下操作:

    variable = {}
    for word in wordlist:
        variable[word] = []
        for boolean in booleanlist:
            variable[word].append(True)
    

    请注意,在这段代码 sn-p 中,每个关键字都有相同的布尔值列表,但这就是你给我们的。


    edit: 删除了 global 声明,它存在只是因为 OP 拥有它。

    【讨论】:

    • 我们将不胜感激有关反对票的一些反馈。
    • 我没有投反对票,但可能是您在代码中留下了global 的事实与此有关。
    • @Matthias 感谢您的意见
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多