Python - 按字符串的数字部分对给定的字符串列表进行排序
给定一个字符串列表。任务是按字符串的数字部分对列表进行排序。
例子:
Input : test_list = [“Gfg34”, “is67”, “be3st”, “f23or”, “ge9eks”]
Output : [‘be3st’, ‘ge9eks’, ‘f23or’, ‘Gfg34’, ‘is67’]
Explanation : 3 < 9 < 23 < 34 < 67, numbers extracted from strings.
Input : test_list = [“Gfg4”, “is67”, “be3st”, “f23or”, “ge9eks”]
Output : [‘be3st’, ‘Gfg4’, ‘ge9eks’, ‘f23or’, ‘is67’]
Explanation : 3 < 4 < 9 < 23 < 67, numbers extracted from strings.
方法 #1:使用 sort() + re.findall()
在这里,我们使用 sort() 执行排序任务,显式函数用于使用 findall() 提取数字。
Python3
# Python3 code to demonstrate working of
# Sort Strings on numerical substrings
# Using sort() + findall()
import re
# helper function to perform sort
def num_sort(test_string):
return list(map(int, re.findall(r'\d+', test_string)))[0]
# initializing list
test_list = ["Gfg34", "is67", "be3st", "f23or", "ge9eks"]
# printing original list
print("The original list is : " + str(test_list))
# calling function
test_list.sort(key=num_sort)
# printing result
print("Strings after numerical Sort : " + str(test_list))
Python3
# Python3 code to demonstrate working of
# Sort Strings on numerical substrings
# Using sort() + lambda + findall()
import re
# initializing list
test_list = ["Gfg34", "is67", "be3st", "f23or", "ge9eks"]
# printing original list
print("The original list is : " + str(test_list))
# findall() getting all integers.
# conversion to integers using map()
test_list.sort(key=lambda test_string : list(
map(int, re.findall(r'\d+', test_string)))[0])
# printing result
print("Strings after numerical Sort : " + str(test_list))
输出:
The original list is : [‘Gfg34’, ‘is67’, ‘be3st’, ‘f23or’, ‘ge9eks’]
Strings after numerical Sort : [‘be3st’, ‘ge9eks’, ‘f23or’, ‘Gfg34’, ‘is67’]
方法 #2:使用 sort() + lambda + findall()
在这里,我们执行了一个类似的函数,但不同之处在于我们使用 lambda函数而不是外部函数来执行排序任务。
蟒蛇3
# Python3 code to demonstrate working of
# Sort Strings on numerical substrings
# Using sort() + lambda + findall()
import re
# initializing list
test_list = ["Gfg34", "is67", "be3st", "f23or", "ge9eks"]
# printing original list
print("The original list is : " + str(test_list))
# findall() getting all integers.
# conversion to integers using map()
test_list.sort(key=lambda test_string : list(
map(int, re.findall(r'\d+', test_string)))[0])
# printing result
print("Strings after numerical Sort : " + str(test_list))
输出:
The original list is : [‘Gfg34’, ‘is67’, ‘be3st’, ‘f23or’, ‘ge9eks’]
Strings after numerical Sort : [‘be3st’, ‘ge9eks’, ‘f23or’, ‘Gfg34’, ‘is67’]