首页 > 解决方案 > ITEM 在 python FOR 循环中是变量

问题描述

我正在尝试找出一种更有效的方法来用 python 编写以下内容。实际上,我想自动创建一个列表,其中包含另一个列表的所有可能组合。

因此,对于下面的示例,将创建 aaa、aab、aac ..... ccc

我想要做的是使组合列表的大小更大,即上升到 a、b、c 和 d。这目前涉及在下面添加另一个 FOR 语句,以便能够运行第 4 个组合。

无论如何,是否可以根据组合列表中的项目数使 FOR 语句的项目列表也可变(类似于我如何使表达式列表变量)?

(我已经查看了使用可变数量的 for 循环创建元组,但如果我们尝试做同样的事情则无法解决,我的其他搜索只找到有关如何制作可迭代变量的问题)

word_ls=['A','B','C']
num_word =[]
loop_len =len(word_ls)


#create the expression which will be used to generate the word listing, which will then be used to match up to the log/ lat co-ordinates
expression=''
for create_string in range(loop_len):    # this replaces >  num_word.append(word_ls[item1] + '.' + word_ls[item2] + '.' + word_ls[item3])

    expression = expression + "word_ls[item{0}".format(create_string+1)+ "] + '.' + "

expression = expression.strip(" + '.' +")

for item1 in range(loop_len):
    for item2 in range(loop_len):    
        for item3 in range(loop_len):
                num_word.append(eval(expression))

标签: pythonfor-loop

解决方案


我相信您正在寻找https://docs.python.org/3/library/itertools.html#itertools.combinations_with_replacement

例如

import itertools
items = ['A', 'B', 'C', 'D']
list(itertools.combinations_with_replacement(items, len(items)))

或者可能是上面@andrepd 建议的产品。

list(itertools.product(items, repeat=len(items)))

这取决于您是想要输出中的 CBA 之类的东西,还是只想要严格排序的 ABC。


推荐阅读