大的循环用于排列



我收到3个整数,"x〃"y";以及";z";。然后最后一个整数是"0";n〃;。

我必须在置换中找到x、y和z之间的所有可能组合,但我只需要保存那些所有值之和不等于n(x+y+z!=n(的组合。

我已经完成了一个大循环。正如您所看到的,打印输出确认该逻辑有效,因此所有可能的组合都是用您使用的任意3个整数找到的。每个组合都临时保存在一个列表中,该列表会不断被覆盖。

我过滤组合,这样你就可以用打印功能只看到那些列表上的值之和不是n的组合。然而,当我想保存找到的每个组合时,它只保存重复的值,而且append方法似乎没有像我需要的那样工作。

# Example:
# 
# Input: x = 1
#        y = 1 
#        z = 1 
#        n = 2
# 
# Output = [[0,0,0],[0,0,1],[0,1,0],[1,0,0],[1,1,1]]
x = int(input())
y = int(input())
z = int(input())
n = int(input())
list_x = [x for x in range(x+1)] #numbers from 0 to x
list_y = [y for y in range(y+1)] #numbers from 0 to y
list_z = [z for z in range(z+1)] #numbers from 0 to z
results = []
#Big for loop which makes the permutation
combination = [0,0,0]
for num_x in list_x:
combination[0] = num_x
for num_y in list_y:
combination[1] = num_y
for num_z in list_z:
combination[2]=num_z
if sum(combination) != n: #Find combinations where total sum != to n
print(combination) #print the combination found
results.append(combination) #save the combination in a list of lists
print(results) #print the lists of lists

任何形式的帮助都将不胜感激。非常感谢。

这是因为combination是对底层列表的引用,这就是您存储在结果中的内容(引用,而不是列表(。这是一个";a-ha";所有Python程序员都会经历的时刻,当他们开始完全摸索语言时:-(

每次更改列表中的元素(与实际的列表相反(时,对它的每个引用似乎也会发生变化,因为只有一个列表

这会让人觉得你在改变早些时候已经设定好的东西,但事实并非如此。

你可以通过看到这一点

>>> xyzzy = [1, 2, 3]  # The list.
>>> plugh = xyzzy      # Copies reference, not list content.
>>> xyzzy[1] = 99      # Changes list content (for BOTH references).
>>> xyzzy ; plugh      # Result: they are both changed.
[1, 99, 3]
[1, 99, 3]
>>> xyzzy = [4, 5, 6]  # Makes xyzzy reference point to NEW list.
>>> xyzzy ; plugh      # Result: they are different.
[4, 5, 6]
[1, 99, 3]

要解决这个问题,你可以去掉combination,只使用类似于的东西

for num_x in list_x:
for num_y in list_y:
for num_z in list_z:
if num_x + num_y + num_z != n:
results.append([num_x, num_y, num_z])
print(results[-1])

它每次都会创建并附加一个新的列表,这样更改就不会随着时间的推移而倒退。


而且,值得一提的是,这也可以通过更Python的列表理解来完成。使用您提供的测试数据,模拟:

list_x, list_y, list_z, n = [0, 1], [0, 1], [0, 1], 2
result = [[x, y, z] 
for x in list_x 
for y in list_y 
for z in list_z 
if x + y + z != n]
print(result)

为了可读性,我把理解分为多行,但它也可以很容易地放在一行,它给出了如下所示的预期输出:

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

最新更新