'How to find out the minimum value in this 2-d list from a specific column
I wish to find out the minimum value from the 3rd column of this particular data set. I have somehow used a "jugaad" method to get the minimum value by setting the variable to higher value. However i wish to know if there is a cleaner alternative to this. I am learning python and i have researched that by using numpy it's easier, however i'd prefer the method without using it.
min=10000
data=[
[514.8,526.9,512,525,27942414],
[527.9,528.5,507.15,499,19353195],
[510,522.2,504.8,520.85,21799071],
[519.95,523.2,512,515.7,18364451],
[510.4,513.85,494.25,501.85,17946821],
]
for i in range(5):
if min>data[i][3]:
min=data[i][3]
print(min)
Solution 1:[1]
You can use generator object to make it cleaner:
m = min(i[3] for i in data)
Output:
499
Also, don't use min as a variable as it is a function name.
Solution 2:[2]
@EliHarold's answer is great. It is very concise. It uses list comprehensions, which I found to be confusing when I first start using Python. Even now, I often prefer to use an explicit for loop.
Here is one brute force method that you could use to first extract the third column, and then use the built-in min function in Python to find the minimum of a 1D list. Python uses zero-based indexes, so if you want the third column, you need to use index 2.
data=[
[514.8,526.9,512,525,27942414],
[527.9,528.5,507.15,499,19353195],
[510,522.2,504.8,520.85,21799071],
[519.95,523.2,512,515.7,18364451],
[510.4,513.85,494.25,501.85,17946821],
]
col3 = []
for row in data:
col3.append(row[2])
minimum = min(col3)
print(minimum)
But even your original code will work if you use an alternate form of the range function*:
range(stop)
range(start, stop[, step])
If we use the second version of the syntax in the form of range(1, step), then we can use the first row to set a minval to compare to and range through second and following rows:
data=[
[514.8,526.9,512,525,27942414],
[527.9,528.5,507.15,499,19353195],
[510,522.2,504.8,520.85,21799071],
[519.95,523.2,512,515.7,18364451],
[510.4,513.85,494.25,501.85,17946821],
]
minval = data[0][2]
for i in range(1, len(data)):
if minval > data[i][2]:
minval = data[i][2]
print(minval)
* OK, strictly speaking range() isn't a function, but a type that is a immutable sequence of numbers.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | bfris |
