python - 逐字逐句阅读 list ,只读最后的

标签 python python-3.x

我有一个要转换成列表的字符串。然后我对该列表中的单词进行计数,并尝试使用该数字(长度)作为计数器,以便我可以将每个单词添加到以数字作为键的字典中。它似乎枚举正确,但它只是读取列表中的最后一个条目,而不是逐字逐句地读取。

知道为什么它只读取列表中的最后一个条目,即“你?”吗?

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)

输出是:

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

输出应该是:

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

最佳答案

你把事情搞得有点太复杂了。您正在为长度中的每个数字遍历整个列表。您可以只使用 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?'}

实际上,上面的代码几乎都不需要,可以重构掉。这段代码做同样的事情:

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?'}

关于python - 逐字逐句阅读 list ,只读最后的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61179349/

相关文章:

python - 为什么 "import module"然后 "from package import module"再次加载模块?

python-3.x - 从 Azure 文件存储读取 NetCDF 文件

python - 相当于 Lua 的 pairs() 用于 Python

python - 如何从 "type"实例中获取类名?

python - 从 dbpedia 检索数据时出错

python - 使用 Pandas 将值从一列复制到另一列

python - flask 异常 "View function mapping is overwriting an existing endpoint function"

Python ValueError : not allowed to raise maximum limit

Mac 上的 Python 3 : ModuleNotFoundError: No module named 'mglearn'

python - 从传递的函数中获取 *args 和 **kwargs