给定两个列表,使用第二个列表对其中一个列表的值进行排序。
null
例如:
Input : list1 = ["a", "b", "c", "d", "e", "f", "g", "h", "i"] list2 = [ 0, 1, 1, 0, 1, 2, 2, 0, 1]Output :['a', 'd', 'h', 'b', 'c', 'e', 'i', 'f', 'g']Input : list1 = ["g", "e", "e", "k", "s", "f", "o", "r", "g", "e", "e", "k", "s"] list2 = [ 0, 1, 1, 0, 1, 2, 2, 0, 1]Output : ['g', 'k', 'r', 'e', 'e', 'g', 's', 'f', 'o']
方法:
- 把这两张单子拉上。
- 使用sorted()基于zip创建一个新的排序列表。
- 使用列表理解从排序的压缩列表中提取每对的第一个元素。
概念: zip()的目的是映射多个容器的类似索引,以便它们可以作为单个实体使用。 以下是上述方法的实施情况:
python
# Python program to sort # one list using # the other list def sort_list(list1, list2): zipped_pairs = zip (list2, list1) z = [x for _, x in sorted (zipped_pairs)] return z # driver code x = [ "a" , "b" , "c" , "d" , "e" , "f" , "g" , "h" , "i" ] y = [ 0 , 1 , 1 , 0 , 1 , 2 , 2 , 0 , 1 ] print (sort_list(x, y)) x = [ "g" , "e" , "e" , "k" , "s" , "f" , "o" , "r" , "g" , "e" , "e" , "k" , "s" ] y = [ 0 , 1 , 1 , 0 , 1 , 2 , 2 , 0 , 1 ] print (sort_list(x, y)) |
输出:
['a', 'd', 'h', 'b', 'c', 'e', 'i', 'f', 'g']['g', 'k', 'r', 'e', 'e', 'g', 's', 'f', 'o']
在上面的代码中,我们有两个列表,第一个列表根据第二个列表的值进行排序。
y = [ 0, 1, 1, 0, 1, 2, 2, 0, 1]
这里首先检查最低值。就像在这个列表中,0是最低的,所以从第一个索引开始,0是最低的,它位于索引0处。因此,索引0的值存储在第一个列表的索引0处。类似地,在索引3处再次找到0,因此第一个列表中索引3的值是索引1。同样的情况一直持续到列表未完成。
方法2:使用字典、列表理解、lambda函数
Python3
def sorting_of_element(list1,list2): # initializing blank dictionary f_1 = {} # initializing blank list final_list = [] # Addition of two list in one dictionary f_1 = {list1[i]: list2[i] for i in range ( len (list2))} # sorting of dictionary based on value f_lst = {k: v for k, v in sorted (f_1.items(), key = lambda item: item[ 1 ])} # Element addition in the list for i in f_lst.keys(): final_list.append(i) return final_list list1 = [ "a" , "b" , "c" , "d" , "e" , "f" , "g" , "h" , "i" ] list2 = [ 0 , 1 , 1 , 0 , 1 , 2 , 2 , 0 , 1 ] sorting_of_element(list1,list2) |
输出:
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END