是否有“列表数据类型”的替代方法,可以对它进行排序并将性能popleft作为双端队列

时间:2019-05-03 01:23:21

标签: python

我使用双端队列代替了popleft的性能列表,但是我在对双端队列进行排序时遇到了问题,因为sorted(deque)将返回一个列表,然后将列表再次转换为双端队列会降低性能

我的代码:

from collections import deque

# items randomly added repeatedly and i want to get the smallest number every time
my_list = ['190-220', '101-189', '221-330', '2110-3300','0-100']
my_list.sort(key=lambda x: int(x.split('-')[0]))

my_list.pop(0) # not efficient since all the remaining items will be shifted in memory

print(my_list)

输出:

['101-189', '190-220', '221-330', '2110-3300']

寻找性能,我尝试使用双端队列,但它不支持就地排序

# sorting, list is the winner here
my_list = sorted(my_list)  # return list, also we can sort in place by my_list.sort()
my_deque = sorted(my_deque)  # unfortunately will return list not deque
my_deque = deque(my_deque) # convert list to deque

# pop first item, deque is the winner here
my_list.pop(0) # not efficient since all the remaining items will be shifted in memory
my_deque.popleft() # it is the efficient way if we need to pop first item

是否有一种替代方法,它既具有“可以作为列表排序”又具有“性能popleft作为双端队列”的优点,

0 个答案:

没有答案