python - 在 python 中转换列表的优雅且廉价的方法

标签 python list list-comprehension

假设我有一个我想增加的数字列表,我只对增加后的值感兴趣,而不是之后的原始值。 就地不复制列表的最pythonic方式是什么?

a = [1, 2, 3]
a = [i+1 for i in a]

生成 a 的中间副本,还是 python 解释器优化了它?

不幸的是,我的 python 知识仍然很肤浅。我的母语是 C++。

最佳答案

无需复制列表,您可以这样做:

In [1]: a = [1, 2, 3]

In [2]: id(a)
Out[2]: 48701592

In [3]: for i in xrange(len(a)): # range(len(a)) for python 3
   ...:     a[i] += 1
   ...:     

In [4]: a
Out[4]: [2, 3, 4]

In [5]: id(a)
Out[5]: 48701592

关于python - 在 python 中转换列表的优雅且廉价的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30634117/

相关文章:

Python:将字符串列表与元组列表进行比较,并根据匹配或不匹配创建新列表

Python,从列表中删除重复项并转换为one2many

python - 词典列表 : loop through key contents

python pandas groupby 第一次约会

python - 连接路径和文件名

c# - 如何根据 List<string> 字段数对 List<List<string>> 进行排序?

java - 在 Java 中创建一个 List<Pair<L,R>> 并支持 .get(key) 方法,就像 map 一样。

javascript - 应用 CSS 将 HTML 内容打印为 PDF [Javascript 或 Django]

python - 将列表中的值分开以形成坐标对

list - 无限制列表的elem函数