The smallest n numbers from the list

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

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

+4
source share
5 answers

You can import heapq

import heapq

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

print(heapq.nsmallest(2,list1))

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

Change 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

Of the two, it seems that sorting the list is faster for small 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 heapqfaster with large sets

+3
source

You can sort the list and grab the first two elements:

sorted(list1)[:2]

, min min ( , 3 ):

list1=[1,15,9,3,6,21,10,11]
m1 = min(list1)
list1.remove(m1)
m2 = min(list1)
print m1, m2 # 1 3
+2

min 1:

list1=[1,15,9,3,6,21,10,11]
mn = min(list1)
mn2 = min(i for i  in list1 if i != mn)    
print((mn,mn2))
(1, 3)

It list1=[1,1,9,3,6,21,10,11], , 1,3, nsmallest 1,1, -, .

, :

def min_two(lst):
    mn1, mn2 = float("inf"),float("inf")
    for ele in lst:
        if ele < mn1:
            mn1 = ele
            continue
        if ele < mn2:
            mn2 = ele
    return mn1, mn2

, heapq.nsmallest:

In [34]:list1=[random.random()  for j in range(10**5)]

In [35]: timeit  heapq.nsmallest(2,list1)             
100 loops, best of 3: 11.6 ms per loop

In [36]: timeit min_two(list1)
100 loops, best of 3: 9.01 ms per loop

In [37]:  %timeit sorted(list1)[:2]
10 loops, best of 3: 42.2 ms per l

:

def min_two_dupes(lst):
    mn1, mn2 = float("inf"),float("inf")
    for ele in lst:
        if ele < mn1:
            mn1 = ele
            continue
        if ele < mn2 and ele != mn1:
            mn2 = ele
    return mn1, mn2

, :

In [48]: list1 = [12, 15, 3, 3, 6, 21, 10, 11]

In [49]: min_two_dupes(list1)
Out[49]: (3, 6)

:

In [52]: timeit min_two_dupes(list1)
100 loops, best of 3: 9.04 ms per loop
+1

2? 2 :

list1=[1,15,9,3,6,21,10,11]
list1.sort()
twoFirst = list1[:2]
nFirst = list1[:n]

, , , - , . , .

+1

If your list cannot contain duplicates, you can use heapq:

from heapq import nsmallest
list1=[1,15,9,3,6,21,10,11] 
smallest = nsmallest(2, list1)

If possible, you can sort the list and then cut it:

smallest = sorted(list1)[0:2]
0
source

Source: https://habr.com/ru/post/1610127/


All Articles