Python:如何循环列表并附加到新列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/53229544/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 20:16:48  来源:igfitidea点击:

Python: How to For Loop a list and append to new list

pythonlistfor-loopappend

提问by sltdev

Practicing my python.

练习我的蟒蛇。

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

任务:循环遍历列表 A 并创建一个新列表,其中仅包含 0-5 之间的列表 A 中的项目。

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]一个答案。

回答by Daniel

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]

回答by John Gordon

You're resetting newto a brand new empty list each time through the loop, which discards any work done in prior iterations.

new每次通过循环都会重置为一个全新的空列表,这会丢弃在先前迭代中完成的任何工作。

Also, in the ifstatement 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

回答by Jab

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]

回答by James

Just a suggestion!

只是一个建议!

  1. The empty list is inside the For Loopmeaning that a new empty list is created every iteration

  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.

    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))
    
  1. 空列表在For 循环内意味着每次迭代都会创建一个新的空列表

  2. '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))
    

回答by timgeb

Three errors:

三个错误:

  1. you are reinstantiating newwith each iteration of the forloop.
  2. you should return newwhen the list is finished building, at the end of the function.
  3. You are appending item, but this is your index. In your code, you would have to append x[item].
  1. 您正在new循环的每次迭代中重新实例化for
  2. 您应该return new在列表构建完成后,在函数的末尾。
  3. 您正在追加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 xdirectly (for item in x: ...).
  2. Use chained comparisons, e.g. 0 < item < 5.
  3. Consider a list comprehension.
  1. 不要索引,x直接循环( for item in x: ...)的项目。
  2. 使用链式比较,例如0 < item < 5
  3. 考虑列表理解。

Code with all three suggestions:

包含所有三个建议的代码:

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