📜  Python - 按元素中的特定数字计数排序

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

Python - 按元素中的特定数字计数排序

给定一个元素列表,按每个元素中的 K 位排序。

例子:

方法 #1:使用列表推导+ str() + count()

在这里,我们使用 sort() 执行排序任务,使用 count() 完成查找频率的任务。

Python3
# Python3 code to demonstrate working of 
# Sort by digit count in elements
# Using list comprehension + count() + str()
  
def count_dig(ele):
      
    # returning digit count
    return str(ele).count(str(K))
  
# initializing list
test_list = [4322, 2122, 123, 1344]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K 
K = 2
  
# calling external sort
test_list.sort(key = count_dig)
  
# printing result 
print("Sorted list : " + str(test_list))


Python3
# Python3 code to demonstrate working of 
# Sort by digit count in elements
# Using sorted() + str() + count() + lambda
  
# initializing list
test_list = [4322, 2122, 123, 1344]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K 
K = 2
  
# sorting using sorted()
# not inplace sort.
res = sorted(test_list, key = lambda ele : str(ele).count(str(K)))
  
# printing result 
print("Sorted list : " + str(res))


输出
The original list is : [4322, 2122, 123, 1344]
Sorted list : [1344, 123, 4322, 2122]

方法 #2:使用sorted() + str() + count() + lambda

在此,我们使用 sorted() 执行排序任务,并使用 lambda函数而不是外部函数来获取排序逻辑。

蟒蛇3

# Python3 code to demonstrate working of 
# Sort by digit count in elements
# Using sorted() + str() + count() + lambda
  
# initializing list
test_list = [4322, 2122, 123, 1344]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K 
K = 2
  
# sorting using sorted()
# not inplace sort.
res = sorted(test_list, key = lambda ele : str(ele).count(str(K)))
  
# printing result 
print("Sorted list : " + str(res))
输出
The original list is : [4322, 2122, 123, 1344]
Sorted list : [1344, 123, 4322, 2122]