简体   繁体   English

逐字阅读列表,只阅读最后一个

[英]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: output 是:

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

Output should be: Output 应该是:

{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:您可以只使用enumerate()来获取索引:

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

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

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