Python 获取列表中少于特定元素的最小元素的最快方法

Python 获取列表中少于特定元素的最小元素的最快方法,python,list,sum,python-2.x,minimum,Python,List,Sum,Python 2.x,Minimum,我最好用一个例子来解释 假设我有一个列表[6,3,5,1,4,2] 从索引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,

我最好用一个例子来解释
假设我有一个列表[6,3,5,1,4,2]

从索引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]
目前使用,

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
def get_diff(lis):
ans=[]
对于索引,枚举中的元素(lis):

number_of_size=len(过滤器(lambda x:x您可以简单地在dict理解中使用列表理解来保留项作为键,小于它的项作为值(并使用
collections.OrderedDict
来保留顺序):

如果要计算这些项目的数量,可以在
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)
>>从集合导入订单数据
>>>def get_diff(lis):
…返回订单数据((项目,总和)(如果i>>def get_diff(lis)中的i为1):
…返回OrderedDict((项,总和(1表示lis中的i[索引:]如果i>>获取_diff(l).values()
[5, 2, 3, 0, 1, 0]
my_list=[6,3,5,1,4,2]
def get_diff(lis):
结果=[]
对于访问,我在枚举(范围(len(lis)):
极限=lis[i]
elem=过滤器(无,[x如果x<限制,则x在lis中为无][visited+1:]
结果追加(len(elem))
返回结果
打印获取差异(我的列表)
#[5, 2, 3, 0, 1, 0]

然而,我觉得这样做效率不高。你有什么感觉?你测试过吗?是的,长度为10**4的列表很容易嘲笑我的代码。虽然在我看来,pythonic并不快,但你的算法的复杂度是O(n²)。如果你想让你的代码更快,你需要使用不同的算法。(我有一个解决方案,但这个边距太小,我写不出来。)不正确。他想从背后的元素数。@hsfzxjy我不这么认为,他没有提到!@hsfzxjy是的,我现在看到了预期的结果,修复了!感谢您的回答。不过,这也是蛮力,我正在寻找一种使用前缀和技术、AVL等优化查找的算法
def get_diff(lis):
       return OrderedDict((item,index),[i for i in lis if i<item]) for index,item in enumerate(lis))
>>> from collections import OrderedDict
>>> def get_diff(lis):
...        return OrderedDict((item,sum(1 for i in lis if i<item)) for item in lis)
>>> 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]