📜  Python - 按最大字符串长度对矩阵进行排序

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

Python - 按最大字符串长度对矩阵进行排序

给定一个矩阵,根据其中字符串的最大长度执行行排序。

方法 #1:使用 sort() + len() + max()

在这种情况下,使用 sort() 执行就地排序,len() 和 max() 计算每行中字符串的最大长度以执行排序。

Python3
# Python3 code to demonstrate working of
# Sort Matrix by Maximum String Length
# Using sort() + len() + max()
  
  
def max_len(row):
  
    # getting Maximum length of string
    return max([len(ele) for ele in row])
  
  
# initializing list
test_list = [['gfg', 'best'], ['geeksforgeeks'],
             ['cs', 'rocks'], ['gfg', 'cs']]
  
# printing original list
print("The original list is : " + str(test_list))
  
# performing sort()
test_list.sort(key=max_len)
  
# printing result
print("Sorted Matrix : " + str(test_list))


Python3
# Python3 code to demonstrate working of
# Sort Matrix by Maximum String Length
# Using sorted() + lambda + max() + len()
  
# initializing list
test_list = [['gfg', 'best'], ['geeksforgeeks'],
             ['cs', 'rocks'], ['gfg', 'cs']]
  
# printing original list
print("The original list is : " + str(test_list))
  
# performing logic using lambda fnc.
res = sorted(test_list, key=lambda row: max([len(ele) for ele in row]))
  
# printing result
print("Sorted Matrix : " + str(res))


输出:

方法 #2:使用sorted() + lambda + max() + len()

在这种情况下,我们使用 lambda函数而不是外部函数来执行过滤最大值的任务。排序的任务是使用 sorted() 来执行的。

蟒蛇3

# Python3 code to demonstrate working of
# Sort Matrix by Maximum String Length
# Using sorted() + lambda + max() + len()
  
# initializing list
test_list = [['gfg', 'best'], ['geeksforgeeks'],
             ['cs', 'rocks'], ['gfg', 'cs']]
  
# printing original list
print("The original list is : " + str(test_list))
  
# performing logic using lambda fnc.
res = sorted(test_list, key=lambda row: max([len(ele) for ele in row]))
  
# printing result
print("Sorted Matrix : " + str(res))

输出: