Reputation: 27
In my code, I am trying to get a list of numbers from a text file and find the smallest two of them. How would i do this?
Myfile = open("RoundOneTotalScores.txt","r")
AScore = ()
BScore = ()
CScore = ()
DScore = ()
EScore = ()
FScore = ()
for line in Myfile:
if "A" in line.split(',')[0]:
AScore = line.split(',')[1]
for line in Myfile:
if "B" in line.split(',')[0]:
BScore = line.split(',')[1]
for line in Myfile:
if "C" in line.split(',')[0]:
CScore = line.split(',')[1]
for line in Myfile:
if "D" in line.split(',')[0]:
DScore = line.split(',')[1]
for line in Myfile:
if "E" in line.split(',')[0]:
EScore = line.split(',')[1]
for line in Myfile:
if "F" in line.split(',')[0]:
FScore = line.split(',')[1]
list1 = [AScore, BScore, CScore, DScore, EScore, FScore]
int(list1)
smallest = min(list1)
print(smallest)
Myfile.close()
The error that keeps coming up is: Traceback (most recent call last): File "", line 1, in EliminateR1() File "D:\NEA Real\Test3.py", line 39, in EliminateR1 int(list1) TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
Upvotes: 0
Views: 1019
Reputation: 54263
Here's an example, assuming your data looks something like this. If you want the minimum, you can use min
. If you want the two smallest values, you can sort
the list and pick the 2 first ones:
txt = """A,1
B,3
F,5
D,4
C,2"""
values = [int(line.split(',')[1]) for line in txt.splitlines()]
print(values)
# [1, 3, 5, 4, 2]
print(min(values))
# 1
print(sorted(values))
# [1, 2, 3, 4, 5]
print(sorted(values)[:2])
# [1, 2]
If you read from a file, you can use :
with open("RoundOneTotalScores.txt") as f:
lines = f.readlines()
values = [int(line.split(',')[1]) for line in lines]
print(values)
# [1, 3, 5, 4, 2]
print(min(values))
# 1
print(sorted(values))
# [1, 2, 3, 4, 5]
print(sorted(values)[:2])
# [1, 2]
print(sorted(values)[2:])
# [3, 4, 5]
Note that collections such as list, dict and sets are defined so that you don't need to define AScore
, BScore
, ...
Upvotes: 1