Python交换列表 [英] Python swapping lists

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

问题描述

在python中,当我将一个列表分配给另一个列表时,例如:

In python, when I assign a list to another, like:

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

现在b和一个指向同一列表的点.现在考虑两个列表,

Now b and a point to the same list. Now considering two lists,

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

现在如何像其他任何数据类型一样交换它们,而又不使两者都指向同一列表?

Now how is it that they are swapped like any other data type and does not end up both pointing to the same list?

推荐答案

就像Python在内部交换项目.检查该程序

Looks like Python internally swaps the items. Check this program

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

def func():
    a, b = b, a

import dis
dis.dis(func)

输出

  4           0 LOAD_FAST                0 (b)
              3 LOAD_FAST                1 (a)
              6 ROT_TWO             
              7 STORE_FAST               1 (a)
             10 STORE_FAST               0 (b)
             13 LOAD_CONST               0 (None)
             16 RETURN_VALUE

因此,Python使用 ROT_TWO 来交换堆栈.因此,现在,最上面的元素是b所指向的引用,下一个是a所指向的引用,然后使用a和b href ="http://docs.python.org/2/library/dis.html#opcode-STORE_FAST" rel ="noreferrer"> STORE_FAST .

So, Python pushes references from b and a in the stack with LOAD_FAST. So, now the top most element is the reference pointed by a and the next one is the reference pointed by b. Then it uses ROT_TWO to swap the top two elements of the stack. So, now, the top most element is the reference pointed by b and the next one is the reference pointed by a and then assigns the top two elements of the stack to a and b respectively with STORE_FAST.

当我们处理的项目数少于4时,这就是在赋值语句中进行排序的方式.

That's how sorting is happening in the assignment statement, when the number of items we deal with is lesser than 4.

如果项数大于或等于四,它将构建一个元组并解压缩值.检查此程序

If the number of items is greater than or equal to four, it builds a tuple and unpacks the values. Check this program

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

def func():
    a, b, c, d  = d, c, b, a

import dis
dis.dis(func)

输出

  4           0 LOAD_FAST                0 (d)
              3 LOAD_FAST                1 (c)
              6 LOAD_FAST                2 (b)
              9 LOAD_FAST                3 (a)
             12 BUILD_TUPLE              4
             15 UNPACK_SEQUENCE          4
             18 STORE_FAST               3 (a)
             21 STORE_FAST               2 (b)
             24 STORE_FAST               1 (c)
             27 STORE_FAST               0 (d)
             30 LOAD_CONST               0 (None)
             33 RETURN_VALUE

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

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