📌  相关文章
📜  Python - 按总字符对矩阵进行排序

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

Python - 按总字符对矩阵进行排序

给定一个字符串矩阵,按总数据排序,即每行的总字符数。

方法 #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))


输出:

方法 #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))

输出: