【问题标题】:Python does not print unique word's multiple positions from stringPython不会从字符串中打印唯一单词的多个位置
【发布时间】:2016-12-19 17:29:06
【问题描述】:

问题是创建一个函数来读取一个字符串并打印一个字典,列出每个 UNIQUE 单词的位置。键是单词,值是它在字符串中的位置列表。

这是一个示例字符串:

One fish two fish red fish blue fish

正确的输出是:

{'two': [2], 'one': [0], 'red': [4], 'fish': [1, 3, 5, 7], 'blue': [6]}

这是我的输出:

{'blue': [6], 'two': [2], 'red': [4], 'fish': [1], 'One': [0]}

如您所见,“fish”一词在此字符串中重复了多次。不只是位置1。我需要添加什么代码才能打印出任何单词的多个位置?

这是我的代码:

def wordPositions(s):
    d = {}

    words = s.split()
    for word in words:
        lst = []
        lst.append(words.index(word))
        d[word] = lst
    return d
print(wordPositions('One fish two fish red fish blue fish'))

【问题讨论】:

  • ...我不认为独特意味着你认为它的意思
  • 如果像“fish”这样的词在您的字符串中重复多次,则它不是唯一的。 “one”、“two”、“red”和“blue”是该字符串中的唯一词。

标签: python string python-3.x dictionary position


【解决方案1】:
from collections import defaultdict
s = 'One fish two fish red fish blue fish'
d = defaultdict(list)
for i, word in enumerate(s.split()):
    d[word.lower()].append(i)

使用collections.defaultdictenumerated.items() 然后是

dict_items([('one', [0]), ('blue', [6]), ('two', [2]), ('red', [4]), ('fish', [1, 3, 5, 7])])

【讨论】:

    【解决方案2】:

    使用enumerate()尝试以下代码:

    s = 'One fish two fish red fish blue fish'
    res = {}
    
    for i, v in enumerate(s.split(' ')):
        if v in res:
            res[v].append(i)
        else:
            res[v] = [i]
    

    输出:

    >>> res
    {'blue': [6], 'fish': [1, 3, 5, 7], 'two': [2], 'red': [4], 'One': [0]}
    

    【讨论】:

      【解决方案3】:

      还有另一个答案...

      >>> words='One fish two fish red fish blue fish'.split()
      >>> counts={}
      >>> for word in set(words):
      ...     counts[word]=[_ for _ in range(len(words)) if words[_]==word]
      ...     
      >>> counts
      {'blue': [6], 'two': [2], 'fish': [1, 3, 5, 7], 'red': [4], 'One': [0]}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-03-16
        • 2019-03-14
        • 2012-09-05
        • 1970-01-01
        • 1970-01-01
        • 2017-04-09
        • 1970-01-01
        相关资源
        最近更新 更多