473,703 Members | 3,348 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

returning index of minimum in a list of lists

Hi all,
Is there a simple python function to return the list index of the
minimum entry in a list of lists?
ie, for [[3,3,3,3], [3,3,3,1], [3,3,3,3]] to return 2,4.
Or, same question but just for a list of numbers, not a list of lists.
Thanks,
Josh

Jun 21 '06 #1
11 8774

JJ********@gmai l.com wrote:
Hi all,
Is there a simple python function to return the list index of the
minimum entry in a list of lists?
ie, for [[3,3,3,3], [3,3,3,1], [3,3,3,3]] to return 2,4.
Or, same question but just for a list of numbers, not a list of lists.
Thanks,
Josh


In your example, you returned 2, 4. Did you mean 1, 3?

mylist[1][3] is the way you would access the "1" in your list of lists.

I don't think this task would have a built in function, but you could
write one in less than 4 lines of code easily.

Jun 21 '06 #2
Le Mercredi 21 Juin 2006 16:54, JJ********@gmai l.com a écrit*:
Hi all,
Is there a simple python function to return the list index of the
minimum entry in a list of lists?
ie, for [[3,3,3,3], [3,3,3,1], [3,3,3,3]] to return 2,4.
Or, same question but just for a list of numbers, not a list of lists.
Thanks,
Josh

In [7]: min([3, 3, 1, 3])
Out[7]: 1

In [8]: min(min(e) for e in [ [3, 3], [3, 3, 1, 3], [3, 3, 3] ])
Out[8]: 1

regards,

--
_____________

Maric Michaud
_____________

Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 426 880 097
Jun 21 '06 #3
JJ********@gmai l.com wrote:
Hi all,
Is there a simple python function to return the list index of the
minimum entry in a list of lists?
ie, for [[3,3,3,3], [3,3,3,1], [3,3,3,3]] to return 2,4.
Or, same question but just for a list of numbers, not a list of lists.
Thanks,
Josh


One way to do this is to generate (value, index-in-main-list,
index-in-secondary-list) tuples and then just take the minimum.

def f(L):
'''Return indices of the first minimum value in a list of lists.'''
return min(
(n, i, j)
for i, L2 in enumerate(L)
for j, n in enumerate(L2)
)[1:]

L = [[3, 3, 3, 3], [3, 3, 3, 1], [3, 3, 3, 3]]

print f(L) # prints (1, 3)

Note: In python (and most other languages) indices begin at 0, so your
return values of (2, 4) wouldn't be correct.

For a list of numbers it's simpler.

L = [3, 3, 3, 1, 3, 3]
print min((n, i) for i, n in enumerate(L))[1] # prints 3

Hope this helps

~Simon

Jun 21 '06 #4
"Maric Michaud" <ma***@aristote .info> wrote in message
news:ma******** *************** *************** *@python.org...
Le Mercredi 21 Juin 2006 16:54, JJ********@gmai l.com a écrit :
Hi all,
Is there a simple python function to return the list index of the
minimum entry in a list of lists?
ie, for [[3,3,3,3], [3,3,3,1], [3,3,3,3]] to return 2,4.
Or, same question but just for a list of numbers, not a list of lists.
Thanks,
Josh

In [7]: min([3, 3, 1, 3])
Out[7]: 1

In [8]: min(min(e) for e in [ [3, 3], [3, 3, 1, 3], [3, 3, 3] ])
Out[8]: 1

regards,

Read the original posting again. The OP does not want the minimum *value*,
but the *index* of the minimum value.

-- Paul
data = [[3,3,3,3], [3,3,3,1], [3,3,3,3]]

def getMinAndIndex( lst):
minval,minidx = lst[0],0
for i,v in enumerate(lst[1:]):
if v < minval:
minval,minidx = v,i+1
return minval,minidx

subMins = [ getMinAndIndex( sub) for sub in data ]
subMin,subIdx = getMinAndIndex( [s[0] for s in subMins ] )

print "min = %d at [%d][%d]" % (subMin, subIdx, subMins[subIdx][1])
Gives:
min = 1 at [1][3]
Jun 21 '06 #5
Thanks so much for your help. I was wondering if there was anything
even simpler, but this will be great.

fo**********@gm ail.com wrote:
JJ********@gmai l.com wrote:
Hi all,
Is there a simple python function to return the list index of the
minimum entry in a list of lists?
ie, for [[3,3,3,3], [3,3,3,1], [3,3,3,3]] to return 2,4.
Or, same question but just for a list of numbers, not a list of lists.
Thanks,
Josh


One way to do this is to generate (value, index-in-main-list,
index-in-secondary-list) tuples and then just take the minimum.

def f(L):
'''Return indices of the first minimum value in a list of lists.'''
return min(
(n, i, j)
for i, L2 in enumerate(L)
for j, n in enumerate(L2)
)[1:]

L = [[3, 3, 3, 3], [3, 3, 3, 1], [3, 3, 3, 3]]

print f(L) # prints (1, 3)

Note: In python (and most other languages) indices begin at 0, so your
return values of (2, 4) wouldn't be correct.

For a list of numbers it's simpler.

L = [3, 3, 3, 1, 3, 3]
print min((n, i) for i, n in enumerate(L))[1] # prints 3

Hope this helps

~Simon


Jun 21 '06 #6
JJ********@gmai l.com wrote:
Is there a simple python function to return the list index of the
minimum entry in a list of lists?
ie, for [[3,3,3,3], [3,3,3,1], [3,3,3,3]] to return 2,4.
Or, same question but just for a list of numbers, not a list of lists.


In Python 2.5:

Python 2.5a2 (trunk:46491M, May 27 2006, 14:43:55) [MSC v.1310 32 bit
(Intel)] on win32
Type "help", "copyright" , "credits" or "license" for more information.
x = [4, 4, 4, 1]
min(xrange(len( x)), key=x.__getitem __) 3 y = [[3,3,3,3], [3,3,3,1], [3,3,3,3]]
min(xrange(len( y)), key=[min(z) for z in y].__getitem__) 1 def multimin(listof lists): .... mins = []
.... min_indices = []
.... for sublist in listoflists:
.... min_index = min(xrange(len( sublist)),
.... key=sublist.__g etitem__)
.... min_indices.app end(min_index)
.... mins.append(sub list[min_index])
.... min_index = min(xrange(len( listoflists)), key=mins.__geti tem__)
.... return min_index, min_indices[min_index]
.... multimin([[3,3,3,3], [3,3,3,1], [3,3,3,3]])

(1, 3)

STeVe
Jun 21 '06 #7
def minIndexFinder( seq):
mins = []
listIndex = 0
result = []
for item in seq:
mins.append([listIndex,min(i tem),item.index (min(item))])
listIndex += 1
lowest = min([x[1] for x in mins])
for item in mins:
if item[1] == lowest:
result.append([item[0], item[2]])
return result

A bit more verbose, but maybe slightly more readable??

I probably should have used enumerate like Paul did.

For the index of the *first* (or only) occurence of the minimum value
in a list of numbers you can just use:

seq.index(min(s eq))

Jun 21 '06 #8
fo**********@gm ail.com wrote:
JJ********@gmai l.com wrote:
Is there a simple python function to return the list index of the
minimum entry in a list of lists?
ie, for [[3,3,3,3], [3,3,3,1], [3,3,3,3]] to return 2,4.
Or, same question but just for a list of numbers, not a list of lists.


One way to do this is to generate (value, index-in-main-list,
index-in-secondary-list) tuples and then just take the minimum.

def f(L):
'''Return indices of the first minimum value in a list of lists.'''
return min(
(n, i, j)
for i, L2 in enumerate(L)
for j, n in enumerate(L2)
)[1:]

L = [[3, 3, 3, 3], [3, 3, 3, 1], [3, 3, 3, 3]]

print f(L) # prints (1, 3)


I think this is probably the nicest solution. Probably doesn't matter,
but it may be worth noting that if you have more than one minimum value,
this will return the one with the lowest indices (where indices are
ordered lexicographical ly)::
L = [[3, 2, 1], [1, 2, 3], [2, 1, 3]]
min((n, i, j)

.... for i, L2 in enumerate(L)
.... for j, n in enumerate(L2))[1:]
(0, 2)

STeVe
Jun 21 '06 #9
Bas
JJ********@gmai l.com wrote:
Thanks so much for your help. I was wondering if there was anything
even simpler, but this will be great.

from numpy import *
a=array([[3,3,3,3], [3,3,3,1], [3,3,3,3]])
where(a==a.min( ))

(array([1]), array([3]))

Probably overkill for your simple problem, but this is a nice
alternative if you do a lot of matrix work.

Bas

Jun 21 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
2483
by: techiepundit | last post by:
I'm a Python newbie who just started learning the language a few weeks ago. So these are beginner questions. I have a list of sockets that I use for select.select calls like this: ReadList,WriteList,EventList = select.select(self.SocketList,,,3) In parallel with that list of sockets I want something that is like a list of socket,PacketFragment pairs. I need this because I could do recv and get part of a sent packet. I want to loop...
11
5809
by: Santosh | last post by:
Dear all , i am writting following code. if(Page.IsPostBack==false) { try { BindSectionDropDownlist();
122
5492
by: C.L. | last post by:
I was looking for a function or method that would return the index to the first matching element in a list. Coming from a C++ STL background, I thought it might be called "find". My first stop was the Sequence Types page of the Library Reference (http://docs.python.org/lib/typesseq.html); it wasn't there. A search of the Library Reference's index seemed to confirm that the function did not exist. A little later I realized it might be called...
9
2050
by: Hank Stalica | last post by:
So I've made a linked list class. I have a function that initiates this class, opens a file, parses it, and then inserts nodes into this temporary class. What I would like to do is then have it return that temporary class so I can assign it to a permanent class in the main program. I've written an assignment operator.
12
5856
by: hiro | last post by:
Hi there, I have a 2 lists.. for simplicities sake lets say the are: l1 = l2 = what I need to do is compare l1 against l2 and return the "position" of where each object in l1 is in l2 ie: pos = 0, 2, 4
6
2181
by: xkenneth | last post by:
Looking to do something similair. I'm working with alot of timestamps and if they're within a couple seconds I need them to be indexed and removed from a list. Is there any possible way to index with a custom cmp() function? I assume it would be something like... list.index(something,mycmp) Thanks!
0
984
by: Kam-Hung Soh | last post by:
On Thu, 17 Apr 2008 12:25:51 +1000, Daniel Fetchinson <fetchinson@googlemail.comwrote: See also Section 4.5. Filtering Lists. List comprehension: == 'somestring']
7
6299
by: Benjamin Goudey | last post by:
I have a very large list of integers representing data needed for a histogram that I'm going to plot using pylab. However, most of these values (85%-95%) are zero and I would like to remove them to reduce the amount of memory I'm using and save time when it comes to plotting the data. To do this, I'm trying to find the best way to remove all of the zero values and produce a list of indices of where the non-zero values used to be. For...
0
8670
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
9017
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8966
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7872
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5922
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4433
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4687
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2455
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2070
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.