[英]What is the most pythonic way to sort a dict with list values?
我正在創建一個值作為整數列表的字典。 對每個鍵的值進行排序的pythonic方法是什么? 在我的方法中,我在排序后覆蓋每個鍵值。
有沒有辦法在插入字典時保持排序,還是先存儲然后對值進行高效排序更好?
my_dict = {
'first': [3,6,99],
'second': [1,-10,100],
'third': [5,0,23,67,29]
}
# my approach
for key, values in my_dict.items():
my_dict[key] = sorted(values)
輸出:
my_dict = {
'first': [3,6,99],
'second': [-10,1,100],
'third': [0,5,23,29,67]
}
pythonic 代碼利用諸如列表推導式或生成器表達式之類的編程模式,嘗試在 C 或 java 中更常用的模式中使用撬棍。 循環是 this 中特別常見的例子。Pythonic 代碼也使用了 PEP20 提到的內聯語法( Beautiful is better than ugly.
Flat is better than nested.
)
首先,您的代碼很好,但要更加 Python 化,您應該使用諸如列表解析/字典解析之類的語法。 我將介紹最有效的方法,它使用最少的代碼行使用 for 循環的 dict comprehension instaed,使其更加 Pythonic,即使 for 循環被認為是 pyhonic list & dict comprehensions 更 Pythonic(它們是扁平語法)。
這是代碼:
my_dict = {
'first': [3,6,99],
'second': [1,-10,100],
'third': [5,0,23,67,29]
}
sorted_dict = {key:sorted(value) for key, value in my_dict.items()}
print(sorted_dict)
輸出:
{'first': [3, 6, 99], 'second': [-10, 1, 100], 'third': [0, 5, 23, 29, 67]}
本地排序不需要再次為鍵賦值。
import random
import time
from copy import deepcopy
def time_it(func):
def inner():
start = time.time()
func()
end = time.time()
print('time used:{} second'.format(end - start))
return inner
def random_l(n):
return [random.randint(0, 100) for _ in range(n)]
my_dict = {
'first': random_l(5),
'second': random_l(5),
'third': random_l(5)
}
my_dict1 = deepcopy(my_dict)
my_dict2 = deepcopy(my_dict)
@time_it
def foo():
print(my_dict1)
for key, values in my_dict1.items():
my_dict1[key] = sorted(values)
print(my_dict1)
@time_it
def bar():
print(my_dict2)
for key, values in my_dict2.items():
sorted(my_dict2[key])
print(my_dict2)
if __name__ == '__main__':
foo()
bar()
{'first': [28, 96, 52, 57, 93], 'second': [17, 89, 76, 30, 36], 'third': [73, 32, 9, 90, 81]}
{'first': [28, 52, 57, 93, 96], 'second': [17, 30, 36, 76, 89], 'third': [9, 32, 73, 81, 90]}
time used:5.3882598876953125e-05 second
{'first': [28, 96, 52, 57, 93], 'second': [17, 89, 76, 30, 36], 'third': [73, 32, 9, 90, 81]}
{'first': [28, 96, 52, 57, 93], 'second': [17, 89, 76, 30, 36], 'third': [73, 32, 9, 90, 81]}
time used:1.621246337890625e-05 second
如果你想要sortedList
sortedcontainers 之類的功能方便,也可以使用bitsect模塊的 insort 功能
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.