Reputation: 21
I am using a two dimensional list in python, I need to find the sum of every item in the list and then return the index with the lowest value.
It should return like this:
Row([[1000, 30], [12, 23], [560, 30, 1]])
1
Row([[10, 9], [20, 1, 2], [1, 3]])
2
This is what I have so far in the shell:
def Row(S):
count=0
for r in range(len(S[0])):
for c in range(len(S)):
count += sum([r])
return r
I can't get the code in the shell to return the indice in a two dimensional list with the lowest sum. Any ideas?
Upvotes: 2
Views: 1585
Reputation: 309881
You can do it in 1 line:
minidx = min(enumerate(data), key=lambda x:sum(x[1]))[0]
Although I would prefer to do the unpacking (instead of indexing the result):
minidx, minlist = min(enumerate(data), key=lambda x:sum(x[1]))
This has the side benefit that you get a quick handle on the list which has the minimum sum ... Although that's easy enough to get once you have the index ...
Upvotes: 1
Reputation: 5089
def row(data):
sums = [sum(x) for x in data]
return sums.index(min(sums))
print row([[1000, 30], [12, 23], [560, 30, 1]])
Upvotes: 0
Reputation: 179392
You can specify a "key" to min
to get the minimum of a list according to some arbitrary criteria. Using this feature, we can do it in just one line:
def min_sum(data):
return min(xrange(len(data)), key=lambda i: sum(data[i]))
Upvotes: 1