【问题标题】:Can someone explain how a dictionary can hold different input values under one key有人可以解释字典如何在一个键下保存不同的输入值
【发布时间】:2016-12-02 19:40:29
【问题描述】:

我有这个简单的循环代码,它接收一行用户输入,并(在将其放入列表后)将单个单词作为键放入字典中,其中 lineCount 编号为值。有人可以解释一下如何调整它,以便如果在不同的行上输入相同的单词,它不会替换字典值,而是添加到它?

import string
lineCount = 1
q = raw_input("enter something")
d = {}

while q != "no":
    q = q.split()
    for word in q:
        d[word] = lineCount
    lineCount += 1
    q = raw_input("enter something")

print d

例如,如果输入是第 1 行的“x y”和第 2 行的“x n”,则字典应打印为“x: 1,2 y:1 n:2”,但目前它只会打印“ x:2 y:1 n:2" 作为与键 x 关联的原始 lineCount 值被替换。如果可能,请避免在解决方案中导入集合,因为我宁愿先了解最长的方式。 非常感谢。

【问题讨论】:

  • 为什么你不使用列表来存储你的值?例如'x': [1, 2]
  • 一个列表会起作用,但由于我希望这段代码能够在每一行处理更长的句子,我认为字典解决方案更合适。 x 和 y 只是一个例子
  • 它仍然是一个字典,但字典中的是行号列表。
  • @user7222454 我的意思不是用列表替换你的字典,只是你的字典项的值是这样的{'x': [1, 2], 'y': [1]}
  • 哦,对了,我明白了。那么一段示例代码会是什么样子呢?

标签: python python-2.7


【解决方案1】:

为您的字典值使用列表,您可以有以下解决方案:

line_count = 1
q = raw_input("enter something: ")
d = {}

while q != "no":
    words = q.split()
    for word in words:
        if word in d and line_count not in d[word]:
            d[word].append(line_count)
        else:
            d[word] = [line_count]
    line_count += 1
    q = raw_input("enter something: ")

print d

输出示例:

>>> python word_lines.py
enter something: hello world
enter something: hello
enter something: world
enter something: sof
enter something: no
{'world': [1, 3], 'hello': [1, 2], 'sof': [4]}

【讨论】:

  • 谢谢,这正是我想要的! :)
  • 我确实有一个快速跟进,如果不是太麻烦的话;在一行中处理同一个单词需要做哪些调整?即如果输入是第 1 行的“hello hello world”和第 2 行的“world”,而不是将值打印为 {'hello': [1,1,2], 'world':[2]} 它只打印 {'hello': [1,2], 'world':[2]}。提前致谢
  • 你只需要在你的情况下像这样添加它:if word in d and line_count not in d[word],看看我编辑的答案。
  • 你也可以使用自动删除重复的集合
  • @ettanany 非常感谢,这有助于我了解更多
【解决方案2】:

如果默认值如下所示,您可以使用 get:

lineCount = 1
q = raw_input("enter something")
d = {}

while q != "no":
    q = q.split()
    for word in q:
        d[word] = d.get(word, 0) + 1
    lineCount += 1
    query = raw_input("enter something")

第一次添加单词时,get不会找到单词,会返回0(默认值)。因此,您将其与 1 相加以更新结果。

【讨论】:

  • 我刚刚运行了这个,它给了我同样的问题,如果输入两次,x 只与它的最新值相关联
  • 将循环内的行更改为:d[word] = d.get(word, []) + [lineCount],每个键的值将是它所在的行列表。
【解决方案3】:

如果您真的想使用字典而不是 ettanany 建议的列表,我建议您将行用作键,将单词用作值,因为行是唯一的,而单词不是。我相信你可以在没有代码示例的情况下解决这个问题:)

【讨论】:

    猜你喜欢
    • 2016-07-29
    • 1970-01-01
    • 1970-01-01
    • 2018-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多