尝试在单行中将可能的数字组合作为列表打印,但是列表输出错误。我的输出是这样的:
[[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)
您应该拿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)]
如果需要大小3的0,1的所有可能组合,请使用itertools中的combinations并将其称为combinations([0,1],3)。这将为您提供所有可能的组合]
更改此行:
result.append(kordinat)
to
result.append(kordinat.copy())
列表被传递为引用,因此如果您更改值,它将在所有地方更改