Python程序在字符串中列出按数字值排序
给定一个字符串列表,任务是编写一个Python程序,根据字符串中存在的数字对列表进行排序。如果没有数字,他们将被带到列表的前面。
Input : test_list = [“gfg is 4”, “all no 1”, “geeks over 7 seas”, “and 100 planets”]
Output : [‘all no 1’, ‘gfg is 4’, ‘geeks over 7 seas’, ‘and 100 planets’]
Explanation : 1 < 4 < 7 < 100, numbers in strings deciding order.
Input : test_list = [“gfg is 4”, “geeks over 7 seas”, “and 100 planets”]
Output : [‘gfg is 4’, ‘geeks over 7 seas’, ‘and 100 planets’]
Explanation : 4 < 7 < 100, numbers in strings deciding order.
方法 1:使用sort() 、 split()和isdigit()
在这里,我们使用 sort() 执行就地排序任务,使用 split() 执行从字符串中获取数字的任务,并使用 isdigit() 完成最终检测。
例子:
Python3
import sys
def num_sort(strn):
# getting number using isdigit() and split()
computed_num = [ele for ele in strn.split() if ele.isdigit()]
# assigning lowest weightage to strings
# with no numbers
if len(computed_num) > 0:
return int(computed_num[0])
return -1
# initializing Matrix
test_list = ["gfg is", "all no 7", "geeks over seas", "and planets 5"]
# printing original list
print("The original list is : " + str(test_list))
# performing sort
test_list.sort(key=num_sort)
# printing result
print("Sorted Strings : " + str(test_list))
Python3
# initializing Matrix
test_list = ["all no 100", "gfg is", "geeks over seas 62", "and planets 3"]
# printing original list
print("The original list is : " + str(test_list))
# performing sorting
# lambda function injecting functionality
res = sorted(test_list, key=lambda strn: -1
if len([ele for ele in strn.split()
if ele.isdigit()]) == 0
else int([ele for ele in strn.split()
if ele.isdigit()][0]))
# printing result
print("Sorted Strings : " + str(res))
输出:
The original list is : [‘gfg is’, ‘all no 7’, ‘geeks over seas’, ‘and planets 5’]
Sorted Strings : [‘gfg is’, ‘geeks over seas’, ‘and planets 5’, ‘all no 7’]
方法 2:使用sorted() 、 lambda 、 split()和isdigit()
在此,lambda函数用于注入使用 sorted() 执行的排序功能。休息每个过程类似于上面解释的方法。
例子:
蟒蛇3
# initializing Matrix
test_list = ["all no 100", "gfg is", "geeks over seas 62", "and planets 3"]
# printing original list
print("The original list is : " + str(test_list))
# performing sorting
# lambda function injecting functionality
res = sorted(test_list, key=lambda strn: -1
if len([ele for ele in strn.split()
if ele.isdigit()]) == 0
else int([ele for ele in strn.split()
if ele.isdigit()][0]))
# printing result
print("Sorted Strings : " + str(res))
输出:
The original list is : [‘all no 100’, ‘gfg is’, ‘geeks over seas 62’, ‘and planets 3’]
Sorted Strings : [‘gfg is’, ‘and planets 3’, ‘geeks over seas 62’, ‘all no 100’]