问题
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()
, becausedict.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