简体   繁体   中英

Read list word for word, only reading the last

I have a string that I'm turning into a list. I then count the words in that list and I'm trying to use that number (length) as a counter so that I can add each word to a dictionary with a number as their key. It seems to enumerate correctly but it's only reading the last entry on the list instead of word for word.

Any idea why it's only reading the last entry on the list ie 'you?'?

mystring = "Hello mate how are you?"

mylist = mystring.split()
lengh = len(mylist)

class my_dictionary(dict): 

    # __init__ function 
    def __init__(self): 
        self = dict() 

    # Function to add key:value 
    def add(self, key, value): 
        self[key] = value 



# Main Function 
dict_obj = my_dictionary() 
for x in range(lengh):
    for line in mylist:
        for word in line.split():
            dict_obj.add(x, line)

print(dict_obj)

output is:

{0: 'you?', 1: 'you?', 2: 'you?', 3: 'you?', 4: 'you?'}

Output should be:

{0: 'Hello?', 1: 'mate?', 2: 'how', 3: 'are', 4: 'you?'}

You are making things a little too complex. You are looping over your whole list for every number in the length. You can just use enumerate() to get the index:

mystring = "Hello mate how are you?"

mylist = mystring.split()

class my_dictionary(dict): 

    def add(self, key, value): 
        self[key] = value 

# Main Function 
dict_obj = my_dictionary() 
for x, word in enumerate(mylist):
    dict_obj.add(x, word)

print(dict_obj)
# {0: 'Hello', 1: 'mate', 2: 'how', 3: 'are', 4: 'you?'}

In reality almost none of the above code is needed and could be refactored out. This code does the same thing:

mystring = "Hello mate how are you?"
words = mystring.split()

dict_obj = dict(enumerate(words))

print(dict_obj)
# {0: 'Hello', 1: 'mate', 2: 'how', 3: 'are', 4: 'you?'}

You want to change your code to be something like this

# Main Function
dict_obj = my_dictionary()
x = 0
for line in mylist:
    dict_obj.add(x, line)
    x += 1

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