eclipse - Get the minimum number out of a file and print. Python -
i have run problem python program. trying list file , print lowest number. eg.
showfile = open("company.txt", 'r') line in showfile: tokens = line.split(',') minvalue = min(tokens[:2]) print("the lowest is", minvalue)
and outputs-
the lowest 33 lowest 18.5 lowest 22
here company.txt -
'huggies', 33, 84 'snugglers', 18.5, 72 'baby love', 22, 96
i quite nooby, awesome.
right now, you're finding lowest number separately in each line. sort of. if want lowest single number in file, should collect numbers or minimum number each line single list, , call min() on list outside loop.
another problem, though, way you're checking numbers tokens[:2]
. stick print tokens
statement after , you'll find you're cutting off second number of each line. if goal cut off company name, you'd use [1:]. problem other answers retain tokens[:2]
line. appear work, because lowest number happens in first column. calling min(tokens[1:])
evaluates number string may produce unexpected results , still includes whitespace, ' 18.5\n'
. compare numbers numbers, wrap them in float().
altogether, this:
showfile = open("company.txt", 'r') numbers = [] line in showfile: tokens = line.split(',') numbers.append(min(float(t) t in tokens[1:])) minvalue = min(numbers) print("the lowest ", minvalue)
Comments
Post a Comment