将for循环转换为while循环以解析行

-3 python for-loop while-loop

我编写了以下for循环来将一些行解析为dict中的键和值.如何将其转换为while循环?

for i in range(len(lines)):
    string = lines[i].rstrip("\n")
    for j in range (len(string)):
        if string[j] == ':':
            user[string[:j]] = string[j+1:]
Run Code Online (Sandbox Code Playgroud)

dav*_*ism 5

您不需要编写的大部分代码来完成拆分每一行:并将结果存储在dict中.只需在线上使用for循环即可.split().

for line in lines:
    key, value = line.strip().split(':', 1)
    user[key] = value
Run Code Online (Sandbox Code Playgroud)

这可以简化为理解.

user = dict(line.strip().split(':', 1) for line in lines)
Run Code Online (Sandbox Code Playgroud)

如果你真的想使用while循环,你可以从列表中弹出值,直到它为空.

while lines:
    key, value = lines.pop().strip().split(':', 1)
    user[key] = value
Run Code Online (Sandbox Code Playgroud)

如果您不想在适当的位置修改列表,请先制作副本并使用该副本.

loop_lines = lines[:]
Run Code Online (Sandbox Code Playgroud)