Reputation: 43
I have run into a problem with my Python program. I am trying to get a list from the file and print the lowest number. eg.
showFile = open("company.txt", 'r')
for line in showFile:
tokens = line.split(',')
minValue = min(tokens[:2])
print("the lowest is", minValue)
and it outputs-
the lowest is 33
the lowest is 18.5
the lowest is 22
Here is the company.txt -
'Huggies', 33, 84
'Snugglers', 18.5, 72
'Baby Love', 22, 96
I am quite nooby, so any help would be awesome.
Upvotes: 0
Views: 2485
Reputation: 2006
Right now, you're finding the lowest number separately in each line. Sort of. If you want the lowest single number in the file, you should collect the numbers or the minimum number from each line into a single list, and call min() on that list outside the for loop.
Another problem, though, is the way you're checking the numbers with tokens[:2]
. Stick a print tokens
statement after this and you'll find that you're cutting off the second number of each line. If the goal was to cut off the company name, you'd use [1:]. This is the problem with the other answers that retain this tokens[:2]
line. They appear to work, but only because the lowest number happens to be in the first column. Calling min(tokens[1:])
also evaluates the number as a string which may produce unexpected results and still includes whitespace, like ' 18.5\n'
. To compare the numbers as numbers, wrap them in float().
Altogether, something like this:
showFile = open("company.txt", 'r')
numbers = []
for line in showFile:
tokens = line.split(',')
numbers.append(min(float(t) for t in tokens[1:]))
minValue = min(numbers)
print("the lowest is ", minValue)
Upvotes: 1
Reputation: 1391
If what you are trying to do is get the lowest value of the entire file, and not for each line, then just do the following:
myLowNumbers = []
showFile = open("company.txt", 'r')
for line in showFile:
tokens = line.split(',')
minValue = min(tokens[:2])
myLowNumbers.append(minValue)
print min(myLowNumbers)
This will continue to add the lowest number from each line to a list, and then return the lowest value from the list once the loop is done. There are certainly more elegant ways to doing this, but until more information is provided, this is the best I can offer.
BTW, don't forget to pay tribute approve of the correct answer by 'up-voting' the correct answers - welcome to SO.
Upvotes: 0
Reputation: 869
You're not really comparing any of the numbers to each other.
This isn't super elegant, but it works.
showFile = open("company.txt", 'r')
lowest = None
for line in showFile:
tokens = line.split(',')
value = min(tokens[:2])
if lowest == None:
lowest = value #set lowest value to first number found
if value < lowest:
lowest = value
print("the lowest is", lowest)
(also I think you're using Python 3.x, I'm using 2.6, just a heads up incase something doesn't quite line up)
Upvotes: 0