【问题标题】:Can't swap the elements in a list, Python无法交换列表中的元素,Python
【发布时间】:2017-10-17 09:59:17
【问题描述】:

我正在尝试使用 while 循环交换列表中的元素。这样该函数一次只能交换两个连续的元素。并在列表中将可能的列表返回给我,但它只打印一个可能的路径。

初始列表是[4,3,2,1]

预期输出 = [[3,4,2,1], [4,2,3,1],[4,3,1,2]]

电流输出 = [[3,2,1,4],[3,2,1,4],[3,2,1,4]]

我的代码是

array = [4,3,2,1]

def possible_paths(Array):
    temp_arr = []
    i=0
    while i < (len(Array) -1):
        temp1 = Array[i]
        Array[i] = Array[i+1]
        Array[i+1] = temp1
        temp_arr.append(Array)
        i = i+1
    return temp_arr

arr1 = []
poss = possible_paths(array)
arr1.append(poss)
print(arr1[:])

【问题讨论】:

  • 目前还不清楚你期望得到什么,以及你得到了什么。
  • 预期的输出是我想要的。而当前输出就是我现在通过该功能得到的结果

标签: python-2.7 python-3.x


【解决方案1】:

我认为您正在寻找的是:

array = [4,3,2,1]

def possible_paths(arr1):
    temp_arr = []
    i=0
    while i < (len(arr1) -1):
        nextpath = arr1[:]
        nextpath[i], nextpath[i+1] = nextpath[i+1], nextpath[i]
        temp_arr.append(nextpath)
        i += 1
    return temp_arr

arr2 = possible_paths(array)
print(arr2[:])

同一个列表被一次又一次地编辑和切换。此外,不需要变量 temp1;您可以通过元组使用多个变量赋值。您不小心使 arr1 成为数组数组的数组; temp_arr 已经是一个数组数组,因此无需将其放入另一个数组中。 “i += 1”只是“i = i+1”的简写。最好使用 arr1 作为函数变量,因为命名通常不使用大写字母。

【讨论】:

    【解决方案2】:
    array = [4,3,2,1]
    def possible_paths(Array):
        temp_arr = []
        i=0
        while i < (len(Array) -1):
            clone_array = Array[:]
            clone_array[i], clone_array[i+1] = clone_array[i+1], clone_array[i]
            temp_arr.append(clone_array)
            i = i+1
        return temp_arr
    
    poss = possible_paths(array)
    print(poss)
    

    输出:[[3, 4, 2, 1], [4, 2, 3, 1], [4, 3, 1, 2]]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-23
      • 2011-06-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多