[英]Fastest way to get minimum elements in a list less than a particular element
I am better off explaining with an example我最好用一个例子来解释
Suppose, I have a list [6,3,5,1,4,2].假设,我有一个列表 [6,3,5,1,4,2]。
Starting from index 0, find all items that are smaller (that have not been marked) than the value at that index.从索引 0 开始,查找所有小于(尚未标记)该索引处的值的项目。
Index 0: [6,3,5,1,4,2]
Elements less than 6: 5{3,5,1,4,2}
Visited array: [1 0 0 0 0 0]
Index 1: [6,3,5,1,4,2]
Elements less than 3: 2 {1,2}
Visited array: [1 1 0 0 0 0]
Index 2: [6,3,5,1,4,2]
Elements less than 5: 3 {1,4,2}
Visited array: [1 1 1 0 0 0]
Index 3: [6,3,5,1,4,2]
Elements less than 1: 0 {NULL}
Visited array: [1 1 1 1 0 0]
Index 4: [6,3,5,1,4,2]
Elements less than 4: 1 {2}
Visited array: [1 1 1 1 1 0]
This yields an array as [5 2 3 0 1 0]
Currently using,目前使用,
def get_diff(lis):
ans=[]
for index,elem in enumerate(lis):
number_of_smaller=len(filter(lambda x:x<elem ,lis[index+1:]))
ans.append(number_of_smaller)
return ans
However, I have a feeling that this will not be efficient.但是,我有一种感觉,这不会有效率。 How do I make it worthy of a huge list?
我如何使它值得一个巨大的清单? Do I smell prefix sums?.
我闻到前缀和了吗? Thanks,
谢谢,
You can simply use a list comprehension within a dict comprehension to preserve the item as the key and the items which are less than it as the value (and use collections.OrderedDict
to preserve the order):您可以简单地在 dict 推导中使用列表推导将项目保留为键,将小于它的项目保留为值(并使用
collections.OrderedDict
保留顺序):
>>> from collections import OrderedDict
>>> def get_diff(lis):
... return OrderedDict((item,[i for i in lis if i<item]) for item in lis)
Since your condition is <
there is no need to exclude the item itself, because that the cost of removing it in comparison is greater than including it.由于您的条件
<
没有必要排除项目本身,因为相比之下,删除它的成本大于包含它的成本。
Also if you want to preserve the indices to you can use enumerate
to loop over your list :此外,如果您想保留索引,您可以使用
enumerate
循环遍历您的列表:
def get_diff(lis):
return OrderedDict((item,index),[i for i in lis if i<item]) for index,item in enumerate(lis))
And if you want to count the number of that items you can use a generator expression within sum
function :如果您想计算这些项目的数量,您可以在
sum
函数中使用生成器表达式:
>>> from collections import OrderedDict
>>> def get_diff(lis):
... return OrderedDict((item,sum(1 for i in lis if i<item)) for item in lis)
NOTE: if you want to count the item less than any item after that (with larger index) you can simply use a indexing in your loop :注意:如果您想计算的项目少于此后的任何项目(具有更大的索引),您可以简单地在循环中使用索引:
>>> def get_diff(lis):
... return OrderedDict((item,sum(1 for i in lis[index:] if i<item)) for index,item in enumerate(lis))
...
>>> get_diff(l).values()
[5, 2, 3, 0, 1, 0]
my_list = [6,3,5,1,4,2]
def get_diff(lis):
result = []
for visited, i in enumerate(range(len(lis))):
limit = lis[i]
elem = filter(None, [x if x < limit else None for x in lis][visited + 1:])
result.append(len(elem))
return result
print get_diff(my_list)
#[5, 2, 3, 0, 1, 0]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.