📌  相关文章
📜  Python - 按回文数对矩阵进行排序

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

Python - 按回文数对矩阵进行排序

给定一个字符串矩阵,按回文字符串计数对每一行进行排序。

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


输出:

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

输出: