簡體   English   中英

Append 多個項目到 python 中的 for 循環列表

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

我有一個嵌套的 python for 循環,需要 append 2 倍的值,下面的代碼是否有效? 或者有更好的 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

假設您想要的 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

另一種(更“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

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

您的代碼是正確的並且符合 PEP8 標准。 我將從 function 塊中刪除my_list並將其作為函數的參數。 我建議使用list.extend()在一行中執行您需要的操作。 為了讓它更像 Pythonic,我會添加輸入提示和函數的docstring 代碼如下所示:

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

我不知道您使用的是哪個 IDE,但是在 Visual Studio Code 上,您可以下載一些擴展以根據函數/類的簽名和鍵入提示自動生成文檔字符串。 而且,還有自動 lint Python 代碼以符合 PEP8 的擴展。

我還會添加一個小測試以確保我的 function 按預期工作。 是這樣的:

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