📜  Python|对元组中的列表进行排序

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

Python|对元组中的列表进行排序

有时,在使用Python元组时,我们可能会遇到一个问题,即我们需要对构成列表的元组进行排序,并且我们需要对它们中的每一个进行排序。让我们讨论可以执行此任务的某些方式。

方法 #1:使用tuple() + sorted() + 生成器表达式
可以使用上述功能的组合来执行此任务。在此,我们使用生成器表达式遍历每个列表并使用sorted()执行排序操作。

# Python3 code to demonstrate working of
# Sort lists in tuple
# Using tuple() + sorted() + generator expression
  
# Initializing tuple
test_tup = ([7, 5, 4], [8, 2, 4], [0, 7, 5])
  
# printing original tuple
print("The original tuple is : " + str(test_tup))
  
# Sort lists in tuple
# Using tuple() + sorted() + generator expression
res = tuple((sorted(sub) for sub in test_tup))
  
# printing result
print("The tuple after sorting lists : " + str(res))
输出 :
The original tuple is : ([7, 5, 4], [8, 2, 4], [0, 7, 5])
The tuple after sorting lists : ([4, 5, 7], [2, 4, 8], [0, 5, 7])

方法 #2:使用map() + sorted()
此方法执行与上述方法类似的任务,但它使用map()将逻辑扩展到元组的每个元素,该任务由上述方法中的列表推导执行。

# Python3 code to demonstrate working of
# Sort lists in tuple
# Using map() + sorted()
  
# Initializing tuple
test_tup = ([7, 5, 4], [8, 2, 4], [0, 7, 5])
  
# printing original tuple
print("The original tuple is : " + str(test_tup))
  
# Sort lists in tuple
# Using map() + sorted()
res = tuple(map(sorted, test_tup))
  
# printing result
print("The tuple after sorting lists : " + str(res))
输出 :
The original tuple is : ([7, 5, 4], [8, 2, 4], [0, 7, 5])
The tuple after sorting lists : ([4, 5, 7], [2, 4, 8], [0, 5, 7])