【问题标题】:Big for loop for permutation用于排列的大 for 循环
【发布时间】:2021-09-28 13:39:47
【问题描述】:

我收到 3 个整数,“x”、“y”和“z”。然后是最后一个整数“n”。

我必须像排列一样找到 x、y 和 z 之间的所有可能组合,但我只需要保存所有值的总和不等于 n (x + y + z != n) 的那些组合.

我已经通过一个大的 for 循环完成了这项工作。如您所见,打印输出确认此逻辑有效,因此可以使用您使用的任何 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

非常感谢任何形式的帮助。谢谢。

【问题讨论】:

    标签: arrays list for-loop append permutation


    【解决方案1】:

    这是因为combination 是对基础列表的引用,这就是您在结果中存储的内容(引用,而不是列表)。这是所有 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])
    

    这样每次都会创建并附加一个 列表,因此更改似乎不会穿越时间。


    而且,就其价值而言,这也可以通过更 Pythonic 的列表理解来完成。使用您提供的测试数据,虚拟化:

    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]]
    

    【讨论】:

      猜你喜欢
      • 2021-05-03
      • 1970-01-01
      • 1970-01-01
      • 2015-12-28
      • 1970-01-01
      • 1970-01-01
      • 2019-08-27
      • 2023-02-02
      相关资源
      最近更新 更多