简体   繁体   English

For和In循环

[英]For and In loops

I want my program to loop through a given list and return all integars that are below 5. 我希望我的程序遍历给定的列表并返回所有低于5的整数。

for some reason it does this but stops as soon as it hits five instead of continuing through the list. 由于某种原因,它会这样做,但是一旦达到5,就会停止,而不是继续执行该列表。

import os
os.system('cls' if os.name == 'nt' else 'clear')


def ace(a):
    d = []
    h = len(a)
    for i in a:
        if i < 5:
            d.append(i)
            continue
        else:
            continue

        return d

m = [1, 2, 4, 3, 3, 5]
print ace(m)

Your code would work fine, however, your return statement is wrongly placed inside the for loop. 您的代码可以正常工作,但是,您的return语句错误地放置在for循环内。 For it to work you would have to remove one indent, placing it outside the for loop but still inside the function. 为了使它起作用,您必须删除一个缩进,将其放在for循环之外但仍在函数内部。 However, there are better and cleaner pythonic ways of doing it. 但是,有更好,更清洁的pythonic方法。 You can use a filter function with a anonymous lambda function: 您可以将过滤器函数与匿名lambda函数一起使用:

def ace(a):  
    return list(filter(lambda x: x < 5, a)) 

m = [1, 2, 4, 3, 3, 5]
print (ace(m))

Or you can use a list comprehension instead of a filter function: 或者,您可以使用列表推导而不是过滤器功能:

def ace(a):  
    return [number for number in a if number < 5] 

 m = [1, 2, 4, 3, 3, 5]
print (ace(m))

you can use the list comprehension for this, which would be easy. 您可以为此使用列表推导,这很容易。 You can return this list. 您可以返回此列表。

Read more about list comprehension here https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions ` 在这里阅读有关列表理解的更多信息https:// docs.python.org/3/ tutorial/ datastructures.html#list-comprehensions`

m = [1, 2, 4, 3, 3, 5]
new_list = [value for value in m if value < 5]`

After this new_list will contain [1, 2, 4, 3, 3] 在此new_list之后将包含[ 1、2、4、3、3 ]

The return statement should be outside the loop. return语句应该在循环之外。

The function can be also be written as: 该函数也可以写成:

def ace(a):
    return [ i for i in a if i<5 ]

First, to fix your code, the main problem is that the return is inside the loop. 首先,要修复您的代码,主要问题是返回值在循环内部。 You should return only after the loop is done. 您应该仅循环完成返回。 Also, you have useless code in the loop: a continue as the last statement does nothing, and you never use the value of h . 另外,循环中没有用到的代码: 继续执行,因为最后一条语句不执行任何操作,并且从不使用h的值。 Shorten it to this: 简化为:

def ace(a):
    d = []
    for i in a:
        if i < 5:
            d.append(i)

    return d

That cleans it up your way. 这样可以清理您的方式。 As others have already noted, Python has a structure called a comprehension that allows you to build lists, tuples, dictionaries, and generators from iteration constructs. 正如其他人已经指出,Python有一种叫做理解 ,可以让你从一个迭代结构构建列表,元组,字典和发电机的结构。

return [_ for _ in a if _ < 5]

Will do the function in a single line. 将在一行中执行该功能。

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

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