Python - 按总位数对元组进行排序
给定一个元组列表,根据元组中的总位数进行排序。
例子:
Input : test_list = [(3, 4, 6, 723), (1, 2), (134, 234, 34)]
Output : [(1, 2), (3, 4, 6, 723), (134, 234, 34)]
Explanation : 2 < 6 < 8, sorted by increasing total digits.
Input : test_list = [(1, 2), (134, 234, 34)]
Output : [(1, 2), (134, 234, 34)]
Explanation : 2 < 8, sorted by increasing total digits.
方法 #1:使用 sort() + len() + sum()
在这里,我们通过字符串转换和 len() 得到元组中每个元素的所有长度的总和。然后 sort() 与 key 一起使用来解决这个问题。
Python3
# Python3 code to demonstrate working of
# Sort Tuples by Total digits
# Using sort() + len() + sum()
def count_digs(tup):
# gets total digits in tuples
return sum([len(str(ele)) for ele in tup ])
# initializing list
test_list = [(3, 4, 6, 723), (1, 2), (12345,), (134, 234, 34)]
# printing original list
print("The original list is : " + str(test_list))
# performing sort
test_list.sort(key = count_digs)
# printing result
print("Sorted tuples : " + str(test_list))
Python3
# Python3 code to demonstrate working of
# Sort Tuples by Total digits
# Using sorted() + lambda + sum() + len()
# initializing list
test_list = [(3, 4, 6, 723), (1, 2), (12345,), (134, 234, 34)]
# printing original list
print("The original list is : " + str(test_list))
# performing sort, lambda function provides logic
res = sorted(test_list, key = lambda tup : sum([len(str(ele)) for ele in tup ]))
# printing result
print("Sorted tuples : " + str(res))
输出
The original list is : [(3, 4, 6, 723), (1, 2), (12345,), (134, 234, 34)]
Sorted tuples : [(1, 2), (12345,), (3, 4, 6, 723), (134, 234, 34)]
方法 #2:使用 sorted() + lambda + sum() + len()
在这里,我们使用 sorted() 执行排序任务,而 lambda函数执行计算元组中总位数的任务。
蟒蛇3
# Python3 code to demonstrate working of
# Sort Tuples by Total digits
# Using sorted() + lambda + sum() + len()
# initializing list
test_list = [(3, 4, 6, 723), (1, 2), (12345,), (134, 234, 34)]
# printing original list
print("The original list is : " + str(test_list))
# performing sort, lambda function provides logic
res = sorted(test_list, key = lambda tup : sum([len(str(ele)) for ele in tup ]))
# printing result
print("Sorted tuples : " + str(res))
输出
The original list is : [(3, 4, 6, 723), (1, 2), (12345,), (134, 234, 34)]
Sorted tuples : [(1, 2), (12345,), (3, 4, 6, 723), (134, 234, 34)]