Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
714 views
in Technique[技术] by (71.8m points)

python - Smallest n numbers from a list

If I have a list list1=[1,15,9,3,6,21,10,11] how do I obtain the smallest 2 integers from that?

min() gives me one number, but what about 2?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can import heapq

import heapq

list1=[1,15,9,3,6,21,10,11]

print(heapq.nsmallest(2,list1))

The limitation with that is if you have a repeated value let's say l=[1,3,5,1], the two smallest values will be [1,1].

Edit 1:

In [2]:
    list1=[1,15,9,3,6,21,10,11]

In [3]:

    %timeit sorted(list1)[:2]
    1000000 loops, best of 3: 1.58 μs per loop
In [5]:

    import heapq
    %timeit heapq.nsmallest(2,list1)
    100000 loops, best of 3: 4.18 μs per loop

From the two, it seems sorting the list is faster for smaller sets.

Edit 2:

In [14]:

    import random
    list1=[[random.random() for i in range(100)] for j in range(100)]
In [15]:

    %timeit sorted(list1)[:2]
    10000 loops, best of 3: 55.6 μs per loop
In [16]:

    import heapq
    %timeit heapq.nsmallest(2,list1)
    10000 loops, best of 3: 27.7 μs per loop

Thanks to Padraic Cunningham, heapq is faster with larger sets


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...