2013-02-10 24 views
24

Belirli bir sütuna göre en az bir sıralama listesi listesi bulmak istiyorum. Örneğin, 2-tuples listesi olarak düzenlenmiş bazı verilerim var.Tuple çiftleri, python kullanarak minimum bulma

data = [ (1, 7.57), (2, 2.1), (3, 1.2), (4, 2.1), (5, 0.01), 
     (6, 0.5), (7, 0.2), (8, 0.6)] 

Sadece dizilerini ikinci sayısını karşılaştırarak veri kümesinin min bulabilirler nasıl? Kabul

yani

data[0][1] = 7.57 
data[1][1] = 2.1 

dakika (veriler) = (5, 0.01)

min(data) döner (1, 7.57), dizin 0 az doğru olmakla birlikte, dizin en az istiyorum 1.

cevap

44
In [2]: min(data, key = lambda t: t[1]) 
Out[2]: (5, 0.01) 

veya:

In [3]: import operator 

In [4]: min(data, key=operator.itemgetter(1)) 
Out[4]: (5, 0.01) 
1

Lev'ın cevabı doğru olsa da, birileri ilk n minimas ile ilgileniyorsa, Sıralama yöntemini de eklemek istedim. düşünmeye Bir şey numpy coolaid içmeye istekli iseniz sıralama en O(N Log N)

data = [ (1, 7.57), (2, 2.1), (3, 1.2), (4, 2.1), (5, 0.01), (6, 0.5), (7, 0.2), (8, 0.6)] 
data.sort(key=lambda x:x[1]) 
print data 

>>> [(5, 0.01), (7, 0.2), (6, 0.5), (8, 0.6), (3, 1.2), (2, 2.1), (4, 2.1), (1, 7.57)] 

https://www.ics.uci.edu/~pattis/ICS-33/lectures/complexitypython.txt

0

olduğu min operasyonun zamanı bu komutları kullanabilirsiniz, O(N) olmasıdır Öğenin en az olduğu yerde tuple'ı almak için:

Bu işi yapan bileşenler, numpy'nin gelişmiş dizi dilimleme ve argsort özellikleridir. .

import numpy as np 
#create a python list of tuples and convert it to a numpy ndarray of floats 
data = np.array([ (1, 7.57), (2, 2.1), (3, 1.2), 
        (4, 2.1), (5, 0.01), (6, 0.5), (7, 0.2), (8, 0.6)]) 

print("data is") 
print(data) 

#Generate sortIndices from second column 
sortIndices = np.argsort(data[:,1]) 

print("sortIndices using index 1 is:") 
print(sortIndices) 
print("The column at index 1 is:") 
print(data[:,1]) 
print("Index 1 put into order using column 1") 
print(data[sortIndices,1]) 
print("The tuples put into order using column 1") 
print(data[sortIndices,:]) 
print("The tuple with minimum value at index 1") 
print(data[sortIndices[0],:]) 
print("The tuple with maximum value at index 1") 
print(data[sortIndices[-1],:]) 

yazdırır Hangi:

data is 
[[ 1. 7.57] 
[ 2. 2.1 ] 
[ 3. 1.2 ] 
[ 4. 2.1 ] 
[ 5. 0.01] 
[ 6. 0.5 ] 
[ 7. 0.2 ] 
[ 8. 0.6 ]] 

sortIndices using index 1 is: 
[4 6 5 7 2 1 3 0] 

The column at index 1 is: 
[ 7.57 2.1 1.2 2.1 0.01 0.5 0.2 0.6 ] 

Index 1 put into order using column 1 
[ 0.01 0.2 0.5 0.6 1.2 2.1 2.1 7.57] 

The tuples put into order using column 1 
[[ 5. 0.01] 
[ 7. 0.2 ] 
[ 6. 0.5 ] 
[ 8. 0.6 ] 
[ 3. 1.2 ] 
[ 2. 2.1 ] 
[ 4. 2.1 ] 
[ 1. 7.57]] 

The tuple with minimum value at index 1 
[ 5. 0.01] 

The tuple with maximum value at index 1 
[ 1. 7.57]