📜  Python - 按大小对字典进行排序

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

Python - 按大小对字典进行排序

给定字典列表,按字典大小进行排序。

方法 #1:使用 len() + sort()

其中,使用sort()进行排序,使用len()获取字典的大小。

Python3
# Python3 code to demonstrate working of
# Sort Dictionaries by Size
# Using len() + sort()
  
# function to get length
def get_len(sub):
  
    # return length
    return len(sub)
  
  
# initializing list
test_list = [{4: 6, 9: 1, 10: 2, 2: 8}, {
    4: 3, 9: 1}, {3: 9}, {1: 2, 9: 3, 7: 4}]
  
# printing original lists
print("The original list is : " + str(test_list))
  
# performing inplace sort of list
test_list.sort(key=get_len)
  
# printing result
print("Sorted List : " + str(test_list))


Python3
# Python3 code to demonstrate working of
# Sort Dictionaries by Size
# Using sorted() + len() + lambda
  
# initializing list
test_list = [{4: 6, 9: 1, 10: 2, 2: 8}, {
    4: 3, 9: 1}, {3: 9}, {1: 2, 9: 3, 7: 4}]
  
# printing original lists
print("The original list is : " + str(test_list))
  
# performing sort using sorted(), lambda for filtering
res = sorted(test_list, key=lambda sub: len(sub))
  
# printing result
print("Sorted List : " + str(res))


输出:

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

在这里,我们使用sorted()执行排序任务,并使用lambda函数代替外部函数来解决获取长度的问题。

蟒蛇3

# Python3 code to demonstrate working of
# Sort Dictionaries by Size
# Using sorted() + len() + lambda
  
# initializing list
test_list = [{4: 6, 9: 1, 10: 2, 2: 8}, {
    4: 3, 9: 1}, {3: 9}, {1: 2, 9: 3, 7: 4}]
  
# printing original lists
print("The original list is : " + str(test_list))
  
# performing sort using sorted(), lambda for filtering
res = sorted(test_list, key=lambda sub: len(sub))
  
# printing result
print("Sorted List : " + str(res))

输出: