📜  Python程序在字符串中列出按数字值排序

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

Python程序在字符串中列出按数字值排序

给定一个字符串列表,任务是编写一个Python程序,根据字符串中存在的数字对列表进行排序。如果没有数字,他们将被带到列表的前面。

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


输出:

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

输出: