假设我有一个我想增加的数字列表,我只对增加后的值感兴趣,而不是之后的原始值。 就地不复制列表的最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/