简体   繁体   English

Append 多个项目到 python 中的 for 循环列表

[英]Append multiple items to a list on a for loop in python

I have a nested python for loop and need to append 2 times a value, is the code below PEP8 valid?我有一个嵌套的 python for 循环,需要 append 2 倍的值,下面的代码是否有效? Or there is a better pythonic way to to write the function?或者有更好的 pythonic 方式来编写 function?

def function():
    empty_list = []
    my_list = ['a', 'b', 'c']
    for letter_1 in my_list: 
        for letter_2 in my_list:
            empty_list.append(letter_1)
            empty_list.append(letter_2)
    return empty_list

Assuming that your desired output is:假设您想要的 output 是:

Desired output:所需的 output:

['a','a','a','b','a','c',  # letter_1, with loop of letter_2
 'b','a','b','b','b','c',  # letter_2, with loop of letter_2
 'c','a','c','b','c','c']  # letter_3, with loop of letter_2

An alternative (more "pythonic"?) way to write your function is to use the itertools library and list comprehensions :另一种(更“pythonic”?)编写 function 的方法是使用itertools库和列表理解

def alt_function(my_list = ['a', 'b', 'c']):
    iterable = chain.from_iterable([a+b for a, b in product(my_list, repeat=2)])
    return list(iterable)
    
alt_function() 

Output Output

['a','a','a','b','a','c',
 'b','a','b','b','b','c',
 'c','a','c','b','c','c']

Your code is right and PEP8 compliant.您的代码是正确的并且符合 PEP8 标准。 I would remove the my_list from the function block and make it a function's parameter.我将从 function 块中删除my_list并将其作为函数的参数。 I would suggest using list.extend() to perform the operation you need in one line.我建议使用list.extend()在一行中执行您需要的操作。 In order to make it a bit more Pythonic I would add typing hints and the function's docstring .为了让它更像 Pythonic,我会添加输入提示和函数的docstring The code would look like this:代码如下所示:

from typing import List

def function(my_list: List) -> List:
    """Function's docstring.

    Args:
        my_list (List): List of characters.

    Returns:
        List: Processed list of characters.
    """
    empty_list = []
    for a in my_list:
        for b in my_list:
            empty_list.extend((a, b))
    return empty_list

I don't know which IDE you use, but on Visual Studio Code you can download some extensions to generate docstrings automatically from your function's/classes' signature and typing hints.我不知道您使用的是哪个 IDE,但是在 Visual Studio Code 上,您可以下载一些扩展以根据函数/类的签名和键入提示自动生成文档字符串。 And also, there's extensions to automatically lint Python code to be PEP8 compliant.而且,还有自动 lint Python 代码以符合 PEP8 的扩展。

I would also add a small test to make sure my function works as expected.我还会添加一个小测试以确保我的 function 按预期工作。 Something like this:是这样的:

assert function(['a', 'b', 'c']) == ['a', 'a', 'a', 'b', 'a', 'c',
                                     'b', 'a', 'b', 'b', 'b', 'c', 'c', 'a', 'c', 'b', 'c', 'c']

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

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