在我的代码中,我试图从文本文件中获取一个数字列表,并找到其中最小的一个。我该怎么做?
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()
不断出现的错误是: Traceback(最近一次调用最后一次): 文件“”,第1行,in EliminateR1() 在EliminateR1中输入第39行的文件“D:\ NEA Real \ Test3.py” INT(列表1) TypeError:int()参数必须是字符串,类字节对象或数字,而不是'list'
答案 0 :(得分:1)
这是一个例子,假设您的数据看起来像这样。如果您想要最低限度,可以使用min
。如果你想要两个最小的值,你可以sort
列表并选择前两个:
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]
如果您从文件中读取,则可以使用:
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]
请注意,列表,字典和集合等集合已定义,因此您无需定义AScore
,BScore
,...