简体   繁体   English

Python:如何进行循环列表并将其追加到新列表

[英]Python: How to For Loop a list and append to new list

Practicing my python. 练习我的python。

Task: Loop through list A and create a new list with only items form list A that's between 0-5. 任务:遍历列表A并创建一个新列表,仅包含列表A中介于0-5之间的项目。

What am I doing wrong here 我在这里做错了什么

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))

I'm just getting [1] as an answer. 我只是得到[1]的答案。

You return command is inside the loop so as soon as it goes through the first case it returns the value exiting the function. 您的返回命令位于循环内部,因此,在遇到第一种情况时,它将立即返回退出函数的值。

Here is an example of what your code should look like 这是您的代码外观的示例

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)

You can achieve the same result by using a list comprehension 您可以通过使用列表理解来获得相同的结果

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

You're resetting new to a brand new empty list each time through the loop, which discards any work done in prior iterations. 您每次通过循环都会将new重置为一个全新的空列表,这会丢弃先前迭代中完成的所有工作。

Also, in the if statement you're calling return , which exits your function immediately, so you never process the remainder of the list. 另外,在if语句中,您正在调用return ,它会立即退出函数,因此您永远不会处理列表的其余部分。

You probably wanted something like this instead: 您可能想要这样的东西:

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

Just my recommendation. 只是我的建议。 You could use filter() here instead of a making your own loop. 您可以在此处使用filter()而不是进行自己的循环。

a = [100, 1, 10, 2, 3, 5, 8, 13, 21, 34, 55, 98]

def new_list(x, low=0, high=5):
    return filter(lambda f: f in range(low, high), x)

Filter returns a new list with elements passing a given predicate and it's equivalent to 筛选器会返回一个新列表,其中的元素将传递给定谓词,它等效于

[item for item in iterable if function(item)]

as per the documentation. 根据文档。

Therefore 因此

print new_list(a)

Results in: 结果是:

[1, 2, 3, 5]

This way you can check any values such as: 这样,您可以检查任何值,例如:

print new_list(a, 5, 10)
[5, 8]

Three errors: 三个错误:

  1. you are reinstantiating new with each iteration of the for loop. 您将在for循环的每次迭代中重新实例化new
  2. you should return new when the list is finished building, at the end of the function. 您应该在函数结束时在列表完成构建后return new
  3. You are appending item , but this is your index. 您正在追加item ,但这是您的索引。 In your code, you would have to append x[item] . 在您的代码中,您将不得不附加x[item]

Code with corrections: 带有更正的代码:

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))

Output: 输出:

[1, 2, 3]

Suggestions: 意见建议:

  1. Don't index, loop over the items of x directly ( for item in x: ... ). 不要指数,环比的项目x直接( for item in x: ... )。
  2. Use chained comparisons, eg 0 < item < 5 . 使用链接比较,例如0 < item < 5
  3. Consider a list comprehension. 考虑一个列表理解。

Code with all three suggestions: 编写所有三个建议的代码:

>>> [item for item in a if 0 < item < 5]
>>> [1, 2, 3]

Just a suggestion! 只是一个建议!

  1. The empty list is inside the For Loop meaning that a new empty list is created every iteration 空列表位于For循环内部, 意味着每次迭代都会创建一个新的空列表

  2. The 'return' is also inside the for loop which is less than ideal, you want it to be returned after the loop has been exhausted and all suitable elements have been appended. 'return'也在for循环内,它不理想,您希望在循环用完并附加所有合适的元素后返回它。

     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(item) return new print(new_list(a)) 

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

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