列出 Python 中 RGB 的所有排列

Listing all permutations of RGB in Python

我正在尝试列出 RGB 所有可能的 27 个 3 字符排列。我的函数如下:

def make_big_RGB():
    rgb = ('r', 'g', 'b')
    comb_list = []
    current_combination = list(rgb) #start with combination (r, g, b)
    for x in range(3):
        current_combination[0] = rgb[x]
        for y in range(3):
            current_combination[1] = rgb[y]
            for z in range(3):
                current_combination[2] = rgb[z]
                comb_list.append(current_combination)
                print('Added' + str(current_combination))
    for _ in comb_list:
        print(_)
make_big_RGB()

结果如下:

Added['r', 'r', 'r']
Added['r', 'r', 'g']
Added['r', 'r', 'b']
Added['r', 'g', 'r']
Added['r', 'g', 'g']
Added['r', 'g', 'b']
Added['r', 'b', 'r']
Added['r', 'b', 'g']
Added['r', 'b', 'b']
Added['g', 'r', 'r']
Added['g', 'r', 'g']
Added['g', 'r', 'b']
Added['g', 'g', 'r']
Added['g', 'g', 'g']
Added['g', 'g', 'b']
Added['g', 'b', 'r']
Added['g', 'b', 'g']
Added['g', 'b', 'b']
Added['b', 'r', 'r']
Added['b', 'r', 'g']
Added['b', 'r', 'b']
Added['b', 'g', 'r']
Added['b', 'g', 'g']
Added['b', 'g', 'b']
Added['b', 'b', 'r']
Added['b', 'b', 'g']
Added['b', 'b', 'b']
['b', 'b', 'b']
['b', 'b', 'b']
['b', 'b', 'b']
['b', 'b', 'b']
['b', 'b', 'b']
['b', 'b', 'b']
['b', 'b', 'b']
['b', 'b', 'b']
['b', 'b', 'b']
['b', 'b', 'b']
['b', 'b', 'b']
['b', 'b', 'b']
['b', 'b', 'b']
['b', 'b', 'b']
['b', 'b', 'b']
['b', 'b', 'b']
['b', 'b', 'b']
['b', 'b', 'b']
['b', 'b', 'b']
['b', 'b', 'b']
['b', 'b', 'b']
['b', 'b', 'b']
['b', 'b', 'b']
['b', 'b', 'b']
['b', 'b', 'b']
['b', 'b', 'b']
['b', 'b', 'b']

最后一个 for 循环打印出想要的结果,但是当我随后尝试打印整个列表时,结果不知何故是一个包含 [b, b, b] 的 27 项的列表。我不明白为什么。

这应该有效:

from itertools import product

list(product('rgb', repeat=3))

问题是

comb_list.append(current_combination)

您正在将 相同的 列表一次又一次地附加到结果列表。因此更改该列表中的值,例如使用 current_combination[0] = rgb[x] 也会更改所有 "other" 列表中的值。

您可以通过在插入之前从该列表创建一个新列表来解决此问题:

comb_list.append(list(current_combination))

或者在将其添加到结果时直接从三个元素创建该列表:

for x in rgb:
    for y in rgb:
        for z in rgb:
            comb_list.append([x, y, z])

或者只对整个事情使用列表理解:

comb_list = [[x, y, z] for x in rgb for y in rgb for z in rgb]

或使用 itertools.product,如其他答案中所述。

一个解决方案:

import itertools

result = itertools.product("rgb",repeat = 3)    
print(list(result))