📌  相关文章
📜  Python|根据总和对元组列表进行排序

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

Python|根据总和对元组列表进行排序

给定一个元组列表,任务是根据元组中元素的总和对元组列表进行排序。

例子:

# 方法一:使用冒泡排序
使用冒泡排序技术我们可以执行排序。请注意,每个元组都是给定列表中的一个元素。使用嵌套循环访问每个元组的元素。这将执行就地排序方法。时间复杂度类似于冒泡排序,即O(n^2).

# Python code to sort list of tuple based on sum of element in tuple.
  
# Input list initialisation
Input = [(4, 5), (2, 3), (6, 7), (2, 8)] 
  
print("The original list of tuple is ")
print(Input)
  
# getting length of list of tuples
lst = len(Input)
  
# Bubble sort
for i in range(lst):
      
    for j in range(lst-i-1):
        if (Input[j][0]+Input[j][1]) > (Input[j+1][0]+Input[j+1][1]):
            Input[j], Input[j+1] = Input[j+1], Input[j]
  
  
# print output
print("\nThe answer is")
print(Input)

输出:

The original list of tuple is 
[(4, 5), (2, 3), (6, 7), (2, 8)]

The answer is
[(2, 3), (4, 5), (2, 8), (6, 7)]

# 方法二:使用 sorted() 方法

这是实现此任务的解决方案的最基本的有效和简短的方法。
在此,我们将 lambda 作为键传递给元组列表。

# Python code to sort list of tuple based on sum of element in tuple.
  
# Input list initialisation
Input = [(4, 5), (2, 3), (6, 7), (2, 8)] 
  
print("The original list of tuple is ")
print(Input)
  
# Passing lambda as key to sort list of tuple
print("\nThe answer is")
print(sorted(Input, key = lambda x:x[0] + x[1]))

输出:

The original list of tuple is 
[(4, 5), (2, 3), (6, 7), (2, 8)]

The answer is
[(2, 3), (4, 5), (2, 8), (6, 7)]

# 方法3:使用sort()方法
通过这种方法进行排序时,元组的实际内容会发生变化,就像冒泡排序一样,执行排序的就地方法。

# Python code to sort list of tuple based on sum of element in tuple.
  
# Input list initialisation
Input = [(4, 5), (2, 3), (6, 7), (2, 8)] 
  
print("The original list of tuple is ")
print(Input)
  
# Passing lambda as key to sort list of tuple
Input.sort(key = lambda x: x[0] + x[1])
  
# Printing output
print("\nThe answer is")
print(Input)

输出:

The original list of tuple is 
[(4, 5), (2, 3), (6, 7), (2, 8)]

The answer is
[(2, 3), (4, 5), (2, 8), (6, 7)]