简体   繁体   中英

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. 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)

{'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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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