简体   繁体   English

Python代码说明需求

[英]Python code explanation need

def array_front9(nums):
    end = len(nums)
    if end > 4:
        end = 4

    for i in range(end):
        if nums[i]==9:
            return True
    return False

I need to understand the above python code and why two return statement in 'for loop'. 我需要了解上面的python代码以及为什么在“ for loop”中有两个return语句。 This is seriously confusing me. 这让我很困惑。

This could be rewritten much simpler (that is, "more pythonic") as this: 可以这样更简单地重写它(即“更多pythonic”):

def array_front9(nums):
   return 9 in nums[:4]

The first half of the code is setting the loop limit to the first 4 elements, or less if the array nums is shorter. 代码的前半部分将循环限制设置为前4个元素,如果数组nums较短,则将循环限制设置为更少。 nums[:4] does essentially the same thing by creating a copy that only contains up to the first 4 elements. nums[:4]通过创建仅包含最多前4个元素的副本来执行基本相同的操作。

The loop is checking to see if the element 9 is found in the loop. 该循环正在检查是否在循环中找到了元素9 If found, it returns immediately with True . 如果找到,它将立即返回True If it's never found, the loop will end and False is returned instead. 如果从未找到,则循环将结束,并返回False This is a longhand form of the in operator, a built-in part of the language. 这是in运算符的一种惯用形式,它是语言的内置部分。

Let me explain: 让我解释:

def array_front9(nums):   # Define the function "array_front9"
    end = len(nums)       # Get the length of "nums" and put it in the variable "end"
    if end > 4:           # If "end" is greater than 4...
        end = 4           # ...reset "end" to 4

    for i in range(end):  # This iterates through each number contained in the range of "end", placing it in the variable "i"
        if nums[i]==9:    # If the "i" index of "nums" is 9...
            return True   # ...return True because we found what we were looking for
    return False          # If we have got here, return False because we didn't find what we were looking for

There are two return-statements in case the loop falls through (finishes) without returning True . 有两种返回语句,以防循环失败(结束)而不返回True

The second return isn't in the for loop . 第二次返回不在for循环中 It provides a return value of False if the loop "falls through", when none of nums[i] equal 9 in that range. nums[i]在该范围内都不等于9时,如果循环“ nums[i] ”,它将提供False的返回值。

At least, that's how you've indented it. 至少,这就是您缩进的方式。

You could rewrite this to be more clear using list slicing: 您可以使用列表切片将其重写为更清晰:

def array_front9(nums):
    sublist = nums[:4]

    if 9 in sublist:
        return True
    else:
        return False

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

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