动漫人物
def fun(lst): for item in lst: cmp = 0 for other in lst: if item < other: cmp -= 1 elif item > other: cmp += 1 if not cmp: return itemnums = [1, 3, 2, 2]您的代码有一个嵌套循环,一个for循环中的一个for循环。外部for循环是for item in lst,内部for循环是:for other in lst:循环看起来像这样:1(outer) - > 1, 3, 2, 2 # 1,3,2,2 are assigned one by one to `other`3(outer) - > 1, 3, 2, 22(outer) - > 1, 3, 2, 22(outer) - > 1, 3, 2, 2它首先从外循环开始,分配给item的值是1,并cmp设置为0。现在,在内部循环中遍历整个列表。分配给other的第一个值是1。现在,它检查它是否大于或小于item(在这种情况下为1),并cmp基于此值增加或减少。在下一次迭代中,现在分配了other 3,再次将其与item(1)比较,并cmp根据该值更改了值。同样,它移至下两个项目2,2。现在出现这种情况:if not cmp: return item它检查的值是否cmp为falsey,如果cmp为0(0为falsey值),则返回该项目,函数终止。(not 0是True在python)如果条件为假,则返回到外部循环,并为该时间item分配值3,然后内部循环按照上面已经描述的那样继续,但事实item是now 3。内部循环实际上所做的是,它实际上比较有多少个项目大于或小于当前项目。1(outer) - > 1, 3, 2, 2 # cmp is -3, because 3,2,2 are bigger than 13(outer) - > 1, 3, 2, 2 # cmp is 3, because 1,2,2 are smaller than 32(outer) - > 1, 3, 2, 2 # cmp is 0, because 3 is greater than 2 and 1 is smaller # than 2, so the condition `if cmp` is True for this case # and the function return 2 (i,e. item)2(outer) - > 1, 3, 2, 2 # this is never reached as function already returned如果所有循环都结束并且cmp永远都不会变为0,则您的函数将返回None(函数的默认返回值)。