Skip to main content
 首页 » 编程设计

python之尝试 For Loop 列表并 append 到新列表,但它在第一项之后返回

2025年05月04日25shanyou

我正在尝试解决这个任务:

Loop through list A and create a new list with only items form list A that's between 0-5.

我在这里做错了什么?

a = [100, 1, 10, 2, 3, 5, 8, 13, 21, 34, 55, 98] 
 
def new_list(x): 
    for item in range(len(x)): 
        new = [] 
        if x[item] < 5 and x[item] > 0: 
            (new.append(item)) 
            return new 
 
print(new_list(a)) 

我只是得到 [1] 作为答案。

请您参考如下方法:

你的 return command 在循环内,所以一旦它通过第一个 case,它就会返回退出函数的值。

这是您的代码的示例

a = [100, 1, 10, 2, 3, 5, 8, 13, 21, 34, 55, 98] 
 
 
def new_list(x): 
    new = [] 
    for item in range(len(x)):             
 
        if x[item] < 5 and x[item] > 0: 
            new.append(x[item]) 
    return new 
 
 
print new_list(a) 

你可以通过使用列表理解来获得相同的结果

def new_list(x): 
    return [item for item in x if 0 < item < 5]