简体   繁体   English

Python sorted()是否实际上会更改要排序的列表?

[英]Does Python sorted() actually CHANGE the list being sorted?

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? 如果将rat_nreads立即分配给空列表,将rat_nreads分配给排序列表有什么意义呢? Does the first line actually change self.markers2nreads.items() in any way? 第一行实际上是否以任何方式更改了self.markers2nreads.items()

No, sorted creates a new list. 否, sorted会创建一个新列表。

So the code you posted doesn't make sense. 因此,您发布的代码没有意义。

Does the first line actually change self.markers2nreads.items() in any way? 第一行实际上是否以任何方式更改了self.markers2nreads.items()

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没有意义。 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. sorted(((self.markers2lens[m],n) for m,n in self.markers2nreads.items()),key = lambda x: x[1])效率更高-使用了生成器,没有临时列表。
  • you should use dict.iteritems() , because dict.items() also creates a unneeded list. 您应该使用dict.iteritems() ,因为dict.items()还会创建不需要的列表。

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])

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.. 希望这可以帮助..

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM