我的循环在第一次迭代后停止

2024-09-28 22:38:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试遍历一个列表字典并返回包含特定整数的值的键。例如,如果我循环遍历{0:[3],1:[3],2:[4,0],3:[1],4:[1,0,2,3]},v=4,它应该返回[2]。 然而,我的代码似乎只考虑第一个键值对,我不明白为什么。如果整数在第一个键值对中,而不是在任何其他键值对中,则它可以工作。下面是我做的函数:

def whence(g, v):
    # Your code here
    lov = []
    count = 0 
    for key, value in g.items(): 
        if v in value:
            lov.append(count)
        count += 1
        print(lov)
        return lov

Tags: 函数代码in列表your字典herevalue
2条回答

您可以在一行中完成:

def whence(g, v):
    return [key for key, values in g.items() if v in values]

return语句缩进太多

def whence(g, v):
    # Your code here
    lov = []
    count = 0 
    for key, value in g.items(): 
        if v in value:
            lov.append(count)
        count += 1
        print(lov)
    return lov

相关问题 更多 >