如何切换列表内容?

时间:2014-05-14 13:51:05

标签: python

我有两个名单,a和b。 我想将a的内容和b的内容重新分配给。

或者换句话说,在用两个列表运行一些操作之后,我想切换列表的名称。因此,名为a的列表现在将命名为b,而名为b的列表现在将命名为a。

这种方式显然是错误的: A = B B = A (因为他们现在都是b)

那么,有没有正确的方法呢?

2 个答案:

答案 0 :(得分:7)

python允许您按如下方式执行此操作:

a, b = b, a

实施例

a = [1,2,3]
b = [4,5,6]
a, b = b, a

>>> print a
[4,5,6]

>>> print b
[1,2,3]

这是因为首先评估右侧的表达式,然后将然后分配给左侧的变量。

答案 1 :(得分:1)

这对您来说可能不是必需的,但要记住:

a = [1, 2, 3]
b = [3, 4, 5]

c = a # now 'c' points to the same list as 'a'
a[0] = 0 # let's change the first element
print a
# [0, 2, 3]
print c

# now let's use multiple assigment:
a, b = b, a
print a
# [3, 4, 5]
print c
# [0, 2, 3]

# list didn't change, but 'a' now point do different list
# but 'c' still point to the same, unchanged list, the one
# that is now referenced by 'b'

以上解决方案速度快,通常最好。但是如果您有其他名称引用的相同列表(或其他可变数据结构),您可以改为替换列表的内容:

a = [1, 2, 3]
b = [3, 4, 5]

c = a 
a[0] = 0 

a[:], b[:] = b[:], a[:] # now we actually swap contents

# 'a' and 'c' still point to the same list,
# but values are from 'b' list
print a 
# [3, 4, 5]
print b
# [0, 2, 3]
print c
# [3, 4, 5]