如果您对python的排序函数中的key参数如何工作?感兴趣,那么本文将是一篇不错的选择,我们将为您详在本文中,您将会了解到关于python的排序函数中的key参数如何工作?的详细内容,我们还将为您解
如果您对python的排序函数中的key参数如何工作?感兴趣,那么本文将是一篇不错的选择,我们将为您详在本文中,您将会了解到关于python的排序函数中的key参数如何工作?的详细内容,我们还将为您解答python key排序的相关问题,并且为您提供关于dayOfTheYear函数如何工作?、Golang函数中的指针参数如何工作?、IPython的魔术贴如何工作?、max函数如何在python中的字典上工作?的有价值信息。
本文目录一览:- python的排序函数中的key参数如何工作?(python key排序)
- dayOfTheYear函数如何工作?
- Golang函数中的指针参数如何工作?
- IPython的魔术贴如何工作?
- max函数如何在python中的字典上工作?
python的排序函数中的key参数如何工作?(python key排序)
说我有
votes = {''Charlie'': 20, ''Able'': 10, ''Baker'': 20, ''Dog'': 15}
我明白
print(sorted(votes.items(), key = lambda x: x[1]))
会导致
[(’Able’,10),(’Dog’,15),(’Baker’,20),(’Charlie’,20)]]
但这如何工作?
答案1
小编典典传递key
给您的函数将获得要排序的每个项目,并返回Python可以排序的“键”。因此,如果要按字符串的 相反顺序
对字符串列表进行排序,可以执行以下操作:
list_of_strings.sort(key=lambda s: s[::-1])
这使您可以指定每个项目的排序依据值,而不必更改项目。这样,您不必构建反向字符串列表,对其进行排序,然后将它们反向反向。
# DON''T do thisdata = [''abc'', ''def'', ''ghi'', ''jkl'']reversed_data = [s[::-1] for s in data]reversed_data.sort()data = [s[::-1] for s in reversed_data]# Do thisdata.sort(key=lambda s: s[::-1])
在您的情况下,代码按元组中的 第二个 项目对每个项目进行排序,而通常它最初将按元组中的第一个项目进行排序,然后中断与第二个项目的联系。
dayOfTheYear函数如何工作?
它需要进行一些更正,并提供您想要的结果。
/* another way extending Date */
class myDate extends Date {
constructor(date) {
super(date);
}
dayOfTheYear() {
let dte = this;
let year = dte.getFullYear();
return Math.floor((dte - new Date(year,0)) / 1000 / 60 / 60 / 24);
}
}
function dayOfTheYear(date) {
let dte = new Date(date);
let year = dte.getFullYear();
/*
this part is all the work,(dte - new Date(year,0)) is actually
current date - first day of the year 0 hour,0 minute,0second,0 millisecond
and return a timestamp in milliseconds,the rest of the divisions are needed to turn milliseconds to days
*/
return Math.floor((dte - new Date(year,0)) / 1000 / 60 / 60 / 24);
}
let dt = new myDate('2020-09-16');
console.log('Child class output day of the year 2020-09-16: '+dt.dayOfTheYear());
console.log('Child class output of full year inherited from parent class: '+dt.getFullYear());
console.log('Function output day of the year 2020-09-16: '+dayOfTheYear('2020-09-16'));
console.log('Function output day of the year 2020-01-11: '+dayOfTheYear('2020-01-11'));
console.log('Function output day of the year 2020-01-01: '+dayOfTheYear('2020-01-01'));
console.log('Function output day of the year 2020-12-31: '+dayOfTheYear('2020-12-31'));
console.log('Function output day of the year 2020-03-16: '+dayOfTheYear('2020-03-16'));