这种在列表中交换值的方式是否在 Python 中使用了额外的内存? [英] Does this way of swapping values in list use extra memory in Python?

查看:29
本文介绍了这种在列表中交换值的方式是否在 Python 中使用了额外的内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

交换列表中值的常用方法是使用临时变量.

temp = l[i]l[i] = l[j]l[j] = 温度

但是在python中你可以这样做:

l[i], l[j] = l[j], l[i]

第二种方法是如何工作的?它是完全相同的过程吗?它使用更少/更多内存吗?

解决方案

import disdef swap_using_temp(a, b):温度 = 一a = bb = 温度def swap_using_unpacking(a, b):a, b = b, a

swap_using_unpacking 不需要额外的内存.

说明:如果您使用 dis 两个函数的模块描述然后你会看到在swap_using_unpacking中有一个字节码指令ROT_TWO 交换堆栈的 2 个最顶层元素(不t 需要第三个变量,因此不会消耗额外的内存).


<预><代码>dis.dis(swap_using_unpacking)11 0 LOAD_FAST 1 (b)2 LOAD_FAST 0 (a)4 ROT_TWO6 STORE_FAST 0 (a)8 STORE_FAST 1 (b)10 LOAD_CONST 0(无)12 RETURN_VALUE


dis.dis(swap_using_temp)5 0 LOAD_FAST 0 (a)2 STORE_FAST 2(温度)6 4 LOAD_FAST 1 (b)6 STORE_FAST 0 (a)7 8 LOAD_FAST 2(温度)10 STORE_FAST 1 (b)12 LOAD_CONST 0 (无)14 RETURN_VALUE

The usual way to swap values in a list is to use a temporary variable.

temp = l[i]
l[i] = l[j]
l[j] = temp

But in python you can do this:

l[i], l[j] = l[j], l[i]

How does this second method work? Is it the exact same process? Does it use less / more memory?

解决方案

import dis


def swap_using_temp(a, b):
    temp = a
    a = b
    b = temp


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

swap_using_unpacking does not require extra memory.

Explanation: If you disassemble the code using dis module of both the function described then you will see that in swap_using_unpacking there is a bytecode instruction ROT_TWO which swaps the 2 topmost elements of the stack(which don't require a third variable hence no extra memory is consumed).



dis.dis(swap_using_unpacking)

 11           0 LOAD_FAST                1 (b)
              2 LOAD_FAST                0 (a)
              4 ROT_TWO
              6 STORE_FAST               0 (a)
              8 STORE_FAST               1 (b)
             10 LOAD_CONST               0 (None)
             12 RETURN_VALUE


dis.dis(swap_using_temp)

  5           0 LOAD_FAST                0 (a)
              2 STORE_FAST               2 (temp)

  6           4 LOAD_FAST                1 (b)
              6 STORE_FAST               0 (a)

  7           8 LOAD_FAST                2 (temp)
             10 STORE_FAST               1 (b)
             12 LOAD_CONST               0 (None)
             14 RETURN_VALUE

这篇关于这种在列表中交换值的方式是否在 Python 中使用了额外的内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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