Python - 按回文数对矩阵进行排序
给定一个字符串矩阵,按回文字符串计数对每一行进行排序。
Input : test_list = [[“nitin”, “meem”, “geeks”], [“peep”], [“gfg”, “is”, “best”], [“sees”, “level”, “mom”, “noon”]]
Output : [[‘peep’], [‘gfg’, ‘is’, ‘best’], [‘nitin’, ‘meem’, ‘geeks’], [‘sees’, ‘level’, ‘mom’, ‘noon’]]
Explanation : 1 = 1 < 2 < 4 is palindromic count order.
Input : test_list = [[“nitin”, “meem”, “geeks”], [“peep”], [“sees”, “level”, “mom”, “noon”]]
Output : [[‘peep’], [‘nitin’, ‘meem’, ‘geeks’], [‘sees’, ‘level’, ‘mom’, ‘noon’]]
Explanation : 1 < 2 < 4 is palindromic count order.
方法 #1:使用reversed() + len() + sort()
在这里,我们使用 sort() 执行就地排序,长度计算和回文检查使用 reversed() 完成。
Python3
# Python3 code to demonstrate working of
# Sort Matrix by Palindrome count
# Using reversed() + len() + sort()
# get palin
def get_palin_freq(row):
# returning length
return len([sub for sub in row if ''.join(list(reversed(sub))) == sub])
# initializing list
test_list = [["nitin", "meem", "geeks"], ["peep"],
["gfg", "is", "best"],
["sees", "level", "mom", "noon"]]
# printing original list
print("The original list is : " + str(test_list))
# performing sort
test_list.sort(key=get_palin_freq)
# printing result
print("Sorted rows : " + str(test_list))
Python3
# Python3 code to demonstrate working of
# Sort Matrix by Palindrome count
# Using sorted() + len() + reversed()
# initializing list
test_list = [["nitin", "meem", "geeks"], ["peep"],
["gfg", "is", "best"], ["sees", "level", "mom", "noon"]]
# printing original list
print("The original list is : " + str(test_list))
# performing sort
# sorted() and lambda used to get 1 sentence approach
res = sorted(test_list, key=lambda row: len(
[sub for sub in row if ''.join(list(reversed(sub))) == sub]))
# printing result
print("Sorted rows : " + str(res))
输出:
The original list is : [[‘nitin’, ‘meem’, ‘geeks’], [‘peep’], [‘gfg’, ‘is’, ‘best’], [‘sees’, ‘level’, ‘mom’, ‘noon’]]
Sorted rows : [[‘peep’], [‘gfg’, ‘is’, ‘best’], [‘nitin’, ‘meem’, ‘geeks’], [‘sees’, ‘level’, ‘mom’, ‘noon’]]
方法 #2:使用 sorted() + len() + reversed()
与上述方法类似,不同之处在于 sorted() 与 lambda函数一起使用,以在没有外部函数调用的情况下单线执行任务。
蟒蛇3
# Python3 code to demonstrate working of
# Sort Matrix by Palindrome count
# Using sorted() + len() + reversed()
# initializing list
test_list = [["nitin", "meem", "geeks"], ["peep"],
["gfg", "is", "best"], ["sees", "level", "mom", "noon"]]
# printing original list
print("The original list is : " + str(test_list))
# performing sort
# sorted() and lambda used to get 1 sentence approach
res = sorted(test_list, key=lambda row: len(
[sub for sub in row if ''.join(list(reversed(sub))) == sub]))
# printing result
print("Sorted rows : " + str(res))
输出:
The original list is : [[‘nitin’, ‘meem’, ‘geeks’], [‘peep’], [‘gfg’, ‘is’, ‘best’], [‘sees’, ‘level’, ‘mom’, ‘noon’]] Sorted rows : [[‘peep’], [‘gfg’, ‘is’, ‘best’], [‘nitin’, ‘meem’, ‘geeks’], [‘sees’, ‘level’, ‘mom’, ‘noon’]]