无法交换列表中的元素,Python [英] Can't swap the elements in a list, Python

查看:73
本文介绍了无法交换列表中的元素,Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to swap elements in a list using while loop. So that the function can only swap two consecutive elements at a time. And return me with the possible list in a list, But it's only printing one possible path.

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

The initial list is[4,3,2,1]

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

Expected Output = [[3,4,2,1], [4,2,3,1],[4,3,1,2]]

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

Current Output = [[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[:])

推荐答案

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

Output : [[3, 4, 2, 1], [4, 2, 3, 1], [4, 3, 1, 2]]

这篇关于无法交换列表中的元素,Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆