Python – 根據字串的數字部分排序給定的字串列表


當需要根據字串的數字部分對給定的字串列表進行排序時,定義了一個使用正則表示式、`map` 方法和 `list` 方法來顯示結果的方法。

示例

以下是演示:

import re
print("The regular expression package has been imported successfully.")

def my_digit_sort(my_list):
   return list(map(int, re.findall(r'\d+', my_list)))[0]

my_list = ["pyt23hon", "fu30n", "lea14rn", 'co00l', 'ob8uje3345t']

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

my_list.sort(key=my_digit_sort)
print("The list has been sorted based on the pre-defined method..")

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

輸出

The regular expression package has been imported successfully.
The list is :
['pyt23hon', 'fu30n', 'lea14rn', 'co00l', 'ob8uje3345t']
The list has been sorted based on the pre-defined method..
The resultant list is :
['co00l', 'ob8uje3345t', 'lea14rn', 'pyt23hon', 'fu30n']

解釋

  • 將所需的包匯入環境。

  • 定義了一個名為 `my_digit_sort` 的方法,它接受一個列表作為引數。

  • 它使用正則表示式和 `re` 包的 `findall` 方法查詢單詞中存在的數字。

  • 這將對映到列表中的所有元素。

  • 這被轉換為列表並作為輸出返回。

  • 在方法外部,定義了一個包含整數的字串列表,並在控制檯上顯示。

  • 此列表根據預定義的方法進行排序。

  • 此輸出顯示在控制檯上。

更新於:2021年9月13日

854 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告