📜  Python|两个列表中的完整性排序

📅  最后修改于: 2022-05-13 01:55:03.133000             🧑  作者: Mango

Python|两个列表中的完整性排序

通常在解决问题的过程中,我们会遇到许多需要对列表进行排序的问题。但有时我们也希望对另一个列表进行排序,以便即使在第一个列表排序后,元素也会自动移动并保持与第一个列表相同的索引。让我们讨论一些可以做到这一点的方法。

方法 #1:使用sorted() + zip() + itemgetter()
结合这三个功能,我们有可能完成任务。 zip 函数将两个列表绑定在一起, sorted函数对列表进行排序, itemgetter函数用于定义我们需要第二个列表移动的指标,在这种情况下是第一个列表。

# Python3 code to demonstrate 
# integrity sorting in two list 
# using sorted() + zip() + itemgetter()
from operator import itemgetter
  
# initializing lists
test_list1 = [3, 4, 9, 1, 6]
test_list2 = [1, 5, 3, 6, 7]
  
# printing original lists
print ("The original list 1 is : " + str(test_list1))
print ("The original list 2 is : " + str(test_list2))
  
# using sorted() + zip() + itemgetter()
# integrity sorting in two list 
res = [list(x) for x in zip(*sorted(zip(test_list1, test_list2),
                                         key = itemgetter(0)))]
  
# printing result 
print ("The lists after integrity sort : " +  str(res))
输出:
The original list 1 is : [3, 4, 9, 1, 6]
The original list 2 is : [1, 5, 3, 6, 7]
The lists after integrity sort : [[1, 3, 4, 6, 9], [6, 1, 5, 7, 3]]


方法 #2:使用sorted() + zip() + lambda function
此方法执行类似的任务,每个函数执行类似的函数,不同之处只是代替 itemgetter函数,lambda函数执行分配基数以对列表进行排序的任务,即本例中的第一个列表。

# Python3 code to demonstrate 
# integrity sorting in two list 
# using sorted() + zip() + lambda function
from operator import itemgetter
  
# initializing lists
test_list1 = [3, 4, 9, 1, 6]
test_list2 = [1, 5, 3, 6, 7]
  
# printing original lists
print ("The original list 1 is : " + str(test_list1))
print ("The original list 2 is : " + str(test_list2))
  
# using sorted() + zip() + lambda function
# integrity sorting in two list 
res = [list(i) for i in zip(*sorted(zip(test_list1, test_list2),
                                  key = lambda dual: dual[0]))]
  
# printing result 
print ("The lists after integrity sort : " +  str(res))
输出:
The original list 1 is : [3, 4, 9, 1, 6]
The original list 2 is : [1, 5, 3, 6, 7]
The lists after integrity sort : [[1, 3, 4, 6, 9], [6, 1, 5, 7, 3]]