[英]Converting List into Dictionary of Sorted Tuples
I've used the following approach many times to generate a list of tuples from the contents of a dictionary:我多次使用以下方法从字典的内容生成元组列表:
dispositions = list(dispositions.items())
In this case, the keys are different types of ways a patient can leave the emergency department, and the values are counts of those types.在这种情况下,键是患者离开急诊室的不同类型的方式,值是这些类型的计数。 Now, I wanted to sort this data based on the second item in each of the tuples, so I tried this:
现在,我想根据每个元组中的第二项对这些数据进行排序,所以我尝试了这个:
dispositions = list(dispositions.items()).sort(key=lambda x: x[1])
To my surprise, when I ran the code, I found that dispositions had been set to None.令我惊讶的是,当我运行代码时,我发现处置已设置为无。 I tried breaking it into two parts, as follows:
我试着把它分成两部分,如下:
dispositions = list(dispositions.items())
dispositions.sort(key=lambda x: x[1])
This works.这行得通。 I got my list of sorted tuples, So, I've already solved my problem.
我得到了排序元组的列表,所以,我已经解决了我的问题。 but I want to know why the first option didn't work so that I can be a better person (better programmers are better people)?
但我想知道为什么第一个选项不起作用,这样我才能成为一个更好的人(更好的程序员就是更好的人)? Can anyone help me out here?
有谁可以帮我离开这里吗?
list.sort
does not return anything. list.sort
不返回任何内容。 So this:所以这:
dispositions = list(dispositions.items()).sort(key=lambda x: x[1])
sets dispositions
to None
.将
dispositions
为None
。
sorted
on the other hand returns a new list.另一方面,
sorted
返回一个新列表。 So you would use:所以你会使用:
dispositions = sorted(dispositions.items(), key=lambda x: x[1])
Which will set dispositions
to a sorted list of tuples.这会将
dispositions
为已排序的元组列表。
The sort
function doesn't work like you might think. sort
function 不像你想象的那样工作。 It does not return a sorted list, it directly modifies the list so it's sorted.它不返回排序列表,它直接修改列表以使其排序。
For instance, say you have this code:例如,假设您有以下代码:
a = [0, 2, 1]
a.sort()
a
will now be changed [0, 1, 2]
. a
现在将更改为[0, 1, 2]
。 Had I used a = a.sort()
rather than just a.sort()
, it would have been set to None
.如果我使用
a = a.sort()
而不仅仅是a.sort()
,它将被设置为None
。
This:这个:
dispositions = list(dispositions.items()).sort(key=lambda x: x[1])
functions the same as this:功能与此相同:
dispositions = list(dispositions.items())
dispositions = dispositions.sort(key=lambda x: x[1])
Which sets dispositions
to the returned value from sort
, which is None
.它将
dispositions
为sort
的返回值,即None
。
On the other hand, this:另一方面,这是:
dispositions = list(dispositions.items())
dispositions.sort(key=lambda x: x[1])
is not setting dispositions
to the value of sort
, it's simply calling the sort
function on dispositions
, which causes the list to be sorted as intended.没有将
dispositions
设置为sort
的值,它只是在dispositions
上调用sort
function ,这会导致列表按预期排序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.