Python - 按总字符对矩阵进行排序
给定一个字符串矩阵,按总数据排序,即每行的总字符数。
Input : test_list = [[“Gfg”, “is”, “Best”], [“Geeksforgeeks”, “Best”], [“ILvGFG”]]
Output : [[‘ILvGFG’], [‘Gfg’, ‘is’, ‘Best’], [‘Geeksforgeeks’, ‘Best’]]
Explanation : 6 < 11 < 17 total characters respectively after sorting.
Input : test_list = [[“Geeksforgeeks”, “Best”], [“ILvGFG”]]
Output : [[‘ILvGFG’], [‘Geeksforgeeks’, ‘Best’]]
Explanation : 6 < 17 total characters respectively after sorting.
方法 #1:使用 sort() + len() + sum()
在这里,我们使用 sort() 执行排序任务,使用 len() 和 sum() 完成获取总字符数的任务。
Python3
# Python3 code to demonstrate working of
# Sort Matrix by total characters
# Using sort() + len() + sum()
def total_chars(row):
# getting total characters
return sum([len(sub) for sub in row])
# initializing list
test_list = [["Gfg", "is", "Best"], ["Geeksforgeeks", "Best"],
["GFg", "4", "good"], ["ILvGFG"]]
# printing original list
print("The original list is : " + str(test_list))
# calling utility fnc
test_list.sort(key=total_chars)
# printing result
print("Sorted results : " + str(test_list))
Python3
# Python3 code to demonstrate working of
# Sort Matrix by total characters
# Using sorted() + lambda
# initializing list
test_list = [["Gfg", "is", "Best"], ["Geeksforgeeks", "Best"],
["GFg", "4", "good"], ["ILvGFG"]]
# printing original list
print("The original list is : " + str(test_list))
# sorted() gives sorted result
# lambda function providing logic
res = sorted(test_list, key = lambda row : sum([len(sub) for sub in row]))
# printing result
print("Sorted results : " + str(res))
输出:
The original list is : [[‘Gfg’, ‘is’, ‘Best’], [‘Geeksforgeeks’, ‘Best’], [‘GFg’, ‘4’, ‘good’], [‘ILvGFG’]]
Sorted results : [[‘ILvGFG’], [‘GFg’, ‘4’, ‘good’], [‘Gfg’, ‘is’, ‘Best’], [‘Geeksforgeeks’, ‘Best’]]
方法 #2:使用sorted() + lambda
其中, sorted() 用于获取排序结果, lambda函数用于代替外部函数来获取排序字符串的逻辑。
蟒蛇3
# Python3 code to demonstrate working of
# Sort Matrix by total characters
# Using sorted() + lambda
# initializing list
test_list = [["Gfg", "is", "Best"], ["Geeksforgeeks", "Best"],
["GFg", "4", "good"], ["ILvGFG"]]
# printing original list
print("The original list is : " + str(test_list))
# sorted() gives sorted result
# lambda function providing logic
res = sorted(test_list, key = lambda row : sum([len(sub) for sub in row]))
# printing result
print("Sorted results : " + str(res))
输出:
The original list is : [[‘Gfg’, ‘is’, ‘Best’], [‘Geeksforgeeks’, ‘Best’], [‘GFg’, ‘4’, ‘good’], [‘ILvGFG’]]
Sorted results : [[‘ILvGFG’], [‘GFg’, ‘4’, ‘good’], [‘Gfg’, ‘is’, ‘Best’], [‘Geeksforgeeks’, ‘Best’]]