Python - 根据元素中的特定位数进行排序


在需要根据元素中的特定位数进行排序时,定义一种方法,该方法将列表元素作为参数并使用“count”和“str”方法来确定结果。

以下是相同的演示:

示例

 在线演示

def sort_count_digits(elements):
   return str(elements).count(str(my_key))

my_list = [4522, 2452, 1233, 2465]

print("The list is :")
print(my_list)

my_key = 2

print("The value of key is ")
print(my_key)

my_list.sort(key = sort_count_digits)

print("The result is :")
print(my_list)

输出

The list is :
[4522, 2452, 1233, 2465]
The value of key is
2
The result is :
[1233, 2465, 4522, 2452]

说明

  • 定义一个名为“sort_count_digits”的方法,该方法将列表元素作为参数。

  • 它将该元素转换为字符串并获取其计数。

  • 这作为输出返回。

  • 定义了一个列表并将其显示在控制台上。

  • 为 K 定义值并将其显示在控制台上。

  • 列表被排序,密钥指定为之前定义的方法。

  • 此列表是显示在控制台上的输出。

更新于:2021-09-06

176 次浏览

开启您的职业生涯

完成课程获得认证

开始
广告
© . All rights reserved.