2013-02-10 61 views
24

का उपयोग करके न्यूनतम ढूंढना मैं किसी दिए गए कॉलम द्वारा क्रमबद्ध टुपल्स की सूची की न्यूनतम सूची खोजना चाहता हूं। उदाहरण के लिए मेरे पास 2-टुपल्स की सूची के रूप में व्यवस्थित कुछ डेटा है।ट्यूपल जोड़े, पाइथन

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[0][1] = 7.57 
data[1][1] = 2.1 

मिनट (डेटा) = (5, 0.01)

min(data) रिटर्न (1, 7.57), जो मैं स्वीकार सूचकांक 0 में से कम से कम के लिए सही है, लेकिन मैं सूचकांक की न्यूनतम चाहते 1.

उत्तर

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

या:

In [3]: import operator 

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

भले ही लेव का जवाब सही है, मैं किसी भी प्रकार की विधि को जोड़ना चाहता था, अगर किसी को पहले n मिनीमास में रूचि है। विचार करने के लिए एक बात है कि min आपरेशन के क्रम O(N) है जहां तरह के 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

है आप numpy coolaid पीने के लिए तैयार हैं, तो आप इन आदेशों का उपयोग कर सकते हैं सूची में टुपल प्राप्त करने के लिए जहां आइटम न्यूनतम है:

इस काम को बनाने वाले तत्वों में numpy की उन्नत सरणी स्लाइसिंग और Argsort विशेषताएं हैं ।

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],:]) 

प्रिंट कौन सा:

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]