简体   繁体   English

将字典的值设置为列表中的索引i + 1时,将item设置为值i的最后一次出现后的项目

[英]When setting the value of a dictionary to an index i + 1 in a list, item is set to the the item after the last occurance of the value i

with open("text.txt", "r") as file:
    contents = file.read().replace('\n',' ')
words = contents.split(' ')


wordsDict = {}
for i in range(len(words) - 1):
    wordsDict[words[i]] = words[i + 1]

def assemble():
    start = words[random.randint(0, len(words))]
    print(start.capitalize())


assemble()

I am currently creating a markov chain-esque project. 我当前正在创建一个markov链式项目。 When I ran this code, I had expected for the dictionary to look as follows: 当我运行这段代码时,我期望字典看起来如下:

(if text.txt read: the cat chased the rat while the dog chased the cat into the rat house) (如果text.txt读为:猫追着老鼠,而狗追着猫进入老鼠屋)

{'the': 'cat', 'cat': 'chased', 'chased': 'the', 'the': 'rat', 'rat': 'while', 'while': 'the', 'the': 'dog', 'dog': 'chased', 'chased': 'the', 'the': 'cat', 'cat': 'into', 'into': 'the', 'the': 'rat', 'rat': 'house'}

but instead, I get 但是相反,我得到了

{'the': 'rat', 'cat': 'into', 'chased': 'the', 'rat': 'house', 'while': 'the', 'dog': 'chased', 'into': 'the'}

If you don't sense a pattern, it's that the value isn't just the next item in the array, it is the next item after the last occurance of the word. 如果您没有感觉到模式,那就是该值不仅是数组中的下一个项目,而且是单词最后一次出现后的下一个项目。 In this case, our first key & value pair is 'the': 'rat' because the last occurance of the is followed by rat. 在这种情况下,我们的第一个键和值对是'the':'rat',因为的最后一次出现是在rat之后。

I have no idea why this happens or how to fix it. 我不知道为什么会这样或如何解决。

The dictionary you wanted isn't valid, you can't duplicate keys. 您想要的字典无效,您不能复制键。 You could try to do this with lists of lists instead. 您可以尝试使用列表列表来代替。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM