在python列表中交换两个元素时出现问题

时间:2017-04-26 13:08:19

标签: python

我写了一个名为edge的类:

class Edge:
    def __init__(self):
        ...
    ...

然后我生成一些边

a1 = Edge()
a2 = Edge()
a3 = Edge()
graph = [a1,a2,a3]

现在我要交换a1,a3。所以我写道:

graph[0],graph[2] = graph[2],graph[0]

我认为图表已经像这样交换过。

>>>graph
>>>[a3,a2,a1]

但结果是图表仍然是原点graph>>>[a1,a2,a3] 所以我想问为什么会这样?有没有其他解决方案来交换图表?

2 个答案:

答案 0 :(得分:0)

graph = [graph[i] for i in [2, 1, 0]] 

或更一般的情况:

def swap(g, i, j):
    tmp = g[i]
    g[i]= g[j]
    g[j] = tmp

graph = swap(graph, i, j)

答案 1 :(得分:0)

它按预期工作。

class Edge:

    def __init__(self):
        self.pred = 0
        self.succ = 0
        self.weight = 1
        self.name = ''

    def __init__(self, p, s, w, strName):
        self.pred = p
        self.succ = s
        self.weight = w
        self.name = strName

a1 = Edge(0,1,1,'a1')
a2 = Edge(1,2,3,'a2')
a3 = Edge(2,3,5,'a3')


a = [a1, a2, a3]
print(a[0].name)
a[1], a[0] = a[0], a[1]
print(a[0].name)

输出是 A1 a2 如预期的那样。