简体   繁体   English

使用 python zip function 将两个列表一起排序

[英]Sorting two lists together in using python zip function

my question is a bit different than the basic sorting two lists together.我的问题与将两个列表基本排序在一起有点不同。

See this code for example:例如,请参阅此代码:

list1=[3,4,2,1,6,1,4,9,3,5,8]
list2=['zombie','agatha','young','old','later','world',
       'corona','nation','domain','issue','happy']
srt=sorted(list(zip(list1,list2)),reverse=True)
print(srt)

The output comes out to be: output 出来是:

[(9, 'nation'), (8, 'happy'), (6, 'later'), (5, 'issue'), 
 (4, 'corona'), (4, 'agatha'), (3, 'zombie'), (3, 'domain'), 
 (2, 'young'), (1, 'world'), (1, 'old')]

Question:- As we can see, for the values which are same in list 1, the elements of my list 2 also get sorted alphabetically in descending order.问题:- 正如我们所看到的,对于列表 1 中相同的值,我的列表 2 的元素也按字母顺序降序排序。 What if I want to sort the list 1 in descending order, and after that, my list 2 elements in ascending order, for which the value of elements of list 1 is same, in some trivial way.如果我想按降序对列表 1 进行排序,然后以某种简单的方式对列表 2 的元素进行升序排序,列表 1 的元素的值相同,该怎么办。

Use key function lambda k: (-k[0], k[1])) :使用密钥 function lambda k: (-k[0], k[1]))

list1 = [3, 4, 2, 1, 6, 1, 4, 9, 3, 5, 8]
list2 = ['zombie', 'agatha', 'young', 'old', 'later', 'world', 'corona', 'nation', 'domain', 'issue', 'happy']
srt = sorted(zip(list1, list2), key=lambda k: (-k[0], k[1]))
print(srt)

Prints:印刷:

[(9, 'nation'), (8, 'happy'), (6, 'later'), (5, 'issue'), (4, 'agatha'), (4, 'corona'), (3, 'domain'), (3, 'zombie'), (2, 'young'), (1, 'old'), (1, 'world')]

It's not pretty but you could do a "double" sorted() , first by the list2 value then reversed list1 value:它不漂亮,但你可以做一个“双” sorted() ,首先是list2值,然后是反转list1值:

from operator import itemgetter

list1=[3,4,2,1,6,1,4,9,3,5,8]
list2=['zombie','agatha','young','old','later','world',
       'corona','nation','domain','issue','happy']


srt=sorted(sorted(zip(list1,list2), key=itemgetter(1)), key=itemgetter(0), reverse=True)
print(srt)

Output: Output:

[(9, 'nation'), (8, 'happy'), (6, 'later'), (5, 'issue'), (4, 'agatha'), (4, 'corona'), (3, 'domain'), (3, 'zombie'), (2, 'young'), (1, 'old'), (1, 'world')]

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

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