Python – 按總字元數對矩陣進行排序


當需要按總字元數對矩陣進行排序時,定義一個方法,其中使用列表解析和“sum”和“len”方法來確定結果。

以下是該方法的演示 -

示例

 線上演示

def total_characters(row):
   return sum([len(element) for element in row])

my_list = [["pyt", "is", "fun"], ["python", "fun"],["py", "4", "good"], ["python"]]

print("The list is :")
print(my_list)

my_list.sort(key=total_characters)

print("The result is :")
print(my_list)

輸出

The list is :
[['pyt', 'is', 'fun'], ['python', 'fun'], ['py', '4', 'good'], ['python']]
The result is :
[['python'], ['py', '4', 'good'], ['pyt', 'is', 'fun'], ['python', 'fun']]

解釋

  • 定義名為“total_characters”的方法,該方法將行作為引數,並返回元素總和作為輸出。

  • 這是透過使用列表解析遍歷元素並獲取每個元素的長度以及將這些長度相加來完成的。

  • 在方法外部,在控制檯上定義並顯示了一個列表。

  • 對該列表進行排序,並透過傳遞所需引數來呼叫該方法。

  • 此結果被分配給一個變數。

  • 這是在控制檯上顯示的輸出。

更新於:2021 年 9 月 6 日

118 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.