3

尝试将单行中可能的数字组合打印为列表,但列表输出错误。我的输出是这样的:

[[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]]

什么时候应该是这样的:

[0, 0, 0]
[0, 0, 1]
[0, 1, 0]
[0, 1, 1]
[1, 0, 0]
[1, 0, 1]
[1, 1, 0]
[1, 1, 1]

我的代码是

if __name__ == '__main__':
    x = 1
    y = 1
    z = 1 
kordinat = ["x","y","z"]
result = []
for xx in range(x+1):
    kordinat[0] = xx
    for yy in range(y+1):
        kordinat[1] = yy
        for zz in range(z+1):
            kordinat[2]= zz
            print(kordinat)
            result.append(kordinat)
print(result)
4

4 回答 4

6

您应该使用itertools.product()

from itertools import product

result = list(product(range(2), repeat=3))
print(result)
# [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]

编辑: 这并不能解释为什么你最终会得到一个充满[1, 1, 1]元素的列表。原因可以在这里找到。通过所有的迭代,您使用一个名为 的列表koordinat。当您将其附加到您的整体列表result时,您始终会附加对同一个对象的引用。因此,您将拥有一个完整的列表,其中包含对同一列表的引用koordinat。因此,在最后一次迭代中更改koordinat[1, 1, 1],也会将列表中的所有引用更改result为此值。这可以最好地看到,当您result每次打印后append()

于 2019-10-14T07:31:00.780 回答
3

改变这一行:

result.append(kordinat)

result.append(kordinat.copy())

列表作为参考传递或分配,因此如果您更改值,它将随处更改。

于 2019-10-14T08:17:00.483 回答
1

要在新行中打印列表元素,pprint如下所示,

>>> from pprint import pprint as pp
>>> pp(result)
[[1, 1, 1],
 [1, 1, 1],
 [1, 1, 1],
 [1, 1, 1],
 [1, 1, 1],
 [1, 1, 1],
 [1, 1, 1],
 [1, 1, 1]]

编辑-1:

假设您正在尝试查找序列的二进制数。在您的示例中,它来自0-7(1 字节或 8 位)。

试试这个,

>>> result = [[int(j) for j in "{0:03b}".format(i)] for i in range(8)]
>>> pp(result)
[[0, 0, 0],
 [0, 0, 1],
 [0, 1, 0],
 [0, 1, 1],
 [1, 0, 0],
 [1, 0, 1],
 [1, 1, 0],
 [1, 1, 1]]
于 2019-10-14T07:16:35.223 回答
1

如果您想要大小为 3 的 0,1 的所有可能组合,请使用来自 itertools 的组合并将其称为combination([0,1],3)。这将为您提供您期望的所有可能的组合

于 2019-10-14T07:29:23.337 回答