📜  Python – 差分排序字符串数字和字母

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

Python – 差分排序字符串数字和字母

给定一个列表字符串,重新排序列表,排序字母后跟排序字符串。

方法 #1:使用 isnumeric() + 循环

在此,我们使用 isnumeric() 将数字和字母字符分开,然后对每个列表进行排序,然后将两个列表进行连接以获得结果。仅适用于 1 位数字字符串。

Python3
# Python3 code to demonstrate working of
# Differential Sort String Numbers and Alphabets
# Using isnumeric() + loop
 
# initializing list
test_list = ["1", "G", "7", "L", "9", "M", "4"]
 
# printing original list
print("The original list is : " + str(test_list))
 
numerics = []
alphabets = []
for sub in test_list:
     
    # checking and inserting in respective container
    if sub.isnumeric():
        numerics.append(sub)
    else:
        alphabets.append(sub)
 
# attaching lists post sort
res = sorted(alphabets) + sorted(numerics)
 
# printing result
print("The Custom sorted result : " + str(res))


Python3
# Python3 code to demonstrate working of
# Differential Sort String Numbers and Alphabets
# Using sorted() + isnumeric()
 
# initializing list
test_list = ["100", "G", "74", "L", "98", "M", "4"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# using int() to type convert to integer
# using sorted() to perform sort operation
res = sorted(test_list, key = lambda ele: (ele.isnumeric(), int(ele) if ele.isnumeric() else ele))
 
# printing result
print("The Custom sorted result : " + str(res))


输出
The original list is : ['1', 'G', '7', 'L', '9', 'M', '4']
The Custom sorted result : ['G', 'L', 'M', '1', '4', '7', '9']

方法#2:使用 sorted() + isumeric()

这是解决此问题的一种线性方法,它使用 isnumeric 检查数字,并且 sorted() 用于执行 sort()。将元素转换为整数和测试,可以处理多于 1 位的数字。

Python3

# Python3 code to demonstrate working of
# Differential Sort String Numbers and Alphabets
# Using sorted() + isnumeric()
 
# initializing list
test_list = ["100", "G", "74", "L", "98", "M", "4"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# using int() to type convert to integer
# using sorted() to perform sort operation
res = sorted(test_list, key = lambda ele: (ele.isnumeric(), int(ele) if ele.isnumeric() else ele))
 
# printing result
print("The Custom sorted result : " + str(res))
输出
The original list is : ['100', 'G', '74', 'L', '98', 'M', '4']
The Custom sorted result : ['G', 'L', 'M', '4', '74', '98', '100']