Does Python sorted() actually CHANGE the list being sorted?

喜你入骨 提交于 2019-12-02 17:09:17

问题


rat_nreads = sorted([(self.markers2lens[m],n) for m,n in self.markers2nreads.items()],key = lambda x: x[1])
rat_nreads, removed = [], []

I saw this code and was really confused; what is the point of assigning rat_nreads to a sorted list if it's going to be assigned to an empty list right after? Does the first line actually change self.markers2nreads.items() in any way?


回答1:


No, sorted creates a new list.

So the code you posted doesn't make sense.

Does the first line actually change self.markers2nreads.items() in any way?

It cannot change, because you have a list comprehension which uses it.

Notes:

  • it doesn't make sense to pass a list to sorted. sorted(((self.markers2lens[m],n) for m,n in self.markers2nreads.items()),key = lambda x: x[1]) is more efficient -- a generator is used, no temporary list.
  • you should use dict.iteritems(), because dict.items() also creates a unneeded list.

To sort the list in place, this is needed:

_list = [(self.markers2lens[m], n) for m, n in self.markers2nreads.iteritems()]
_list.sort(key=lambda x: x[1])



回答2:


The items remain in the same place in memory but a new list is created:

a = [1, 0, 2]
a1 = id(a[0])

b = sorted(a)
b1 = id(b[1])

print a1 == b1
>>>True

Hope this helps..



来源:https://stackoverflow.com/questions/30706746/does-python-sorted-actually-change-the-list-being-sorted

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!