📜  Python|排序备用数字和字母列表

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

Python|排序备用数字和字母列表

有时,在列表中执行排序时,我们会遇到一个问题,即我们需要执行特定类型的排序,在这种排序中,我们需要以数字和字母按顺序排序的替代方式进行排序。让我们讨论可以执行此任务的某些方式。

方法#1:使用isalpha() + isnumeric() + zip_longest()
上述方法的组合可用于执行此任务。在此,我们将数字和字母分开,然后分别对它们进行排序并使用 zip_longest() 连接。

# Python3 code to demonstrate 
# Sort alternate numeric and alphabet list
# using isalpha() + isnumeric() + zip_longest()
from itertools import zip_longest
  
# Initializing list
test_list = ['3', 'B', '2', 'A', 'C', '1']
  
# printing original list
print("The original list is : " + str(test_list))
  
# Sort alternate numeric and alphabet list
# using isalpha() + isnumeric() + zip_longest()
num_list = sorted(filter(str.isnumeric, test_list), 
                       key = lambda sub: int(sub))
  
chr_list = sorted(filter(str.isalpha, test_list))
res = [ele for sub in zip_longest(num_list, chr_list)
                              for ele in sub if ele]
      
# printing result 
print ("List after performing sorting : " + str(res))
输出 :
The original list is : ['3', 'B', '2', 'A', 'C', '1']
List after performing sorting : ['1', 'A', '2', 'B', '3', 'C']

方法 #2:使用sorted() + key + lambda + isnumeric()
上述方法的组合可用于执行此任务。在此,我们使用 ord() 和 lambda 函数以交替方式执行排序,使用 isnumeric() 进行测试。

# Python3 code to demonstrate 
# Sort alternate numeric and alphabet list
# using sorted() + key + lambda + isnumeric()
from itertools import zip_longest
  
# Initializing list
test_list = ['3', 'B', '2', 'A', 'C', '1']
  
# printing original list
print("The original list is : " + str(test_list))
  
# Sort alternate numeric and alphabet list
# using sorted() + key + lambda + isnumeric()
res = sorted(test_list, key = lambda ele : (int(ele), 0)
      if ele.isnumeric()
      else ((ord(ele) - 64) % 26, 1))
  
# printing result 
print ("List after performing sorting : " + str(res))
输出 :
The original list is : ['3', 'B', '2', 'A', 'C', '1']
List after performing sorting : ['1', 'A', '2', 'B', '3', 'C']