Python index()函数不使用';t工作,较长的也不能找到包含最大/最小编号的行的编号
我的代码没有做它应该做的事情——查找max/min并打印哪一行包含这些值 它确实会找到最大/最小值,但不会打印预期的行。这是我的密码:Python index()函数不使用';t工作,较长的也不能找到包含最大/最小编号的行的编号,python,python-3.x,indexing,Python,Python 3.x,Indexing,我的代码没有做它应该做的事情——查找max/min并打印哪一行包含这些值 它确实会找到最大/最小值,但不会打印预期的行。这是我的密码: eqlCounter = 0 octals = [] with open("D:\matura\Matura2017\Dane_PR2\liczby.txt", "r") as f: for x in f: lines = f.readline() splited = lines.s
eqlCounter = 0
octals = []
with open("D:\matura\Matura2017\Dane_PR2\liczby.txt", "r") as f:
for x in f:
lines = f.readline()
splited = lines.split()
toInt = int(splited[1], 8) #oct to int(dec)
octals.append(toInt)
if int(splited[0]) == toInt:
eqlCounter += 1
low = min(octals)
maxx = max(octals)
print("same nmbrs: ", eqlCounter) #a
print("min: ", min(octals),"at: ",octals.index(low))
print("max: ", max(octals),"at: ",octals.index(maxx))
每行包含一个十进制数(第1列)和一个八进制数(第2列)。我的代码找到最小和最大的八进制数,然后以小数形式打印出来。在显示包含此类值的行之前,它工作正常
40829 134773
28592 31652
15105 123071
18227 36440
51074 122407
23893 117256
30785 100453
39396 11072
50492 105177
36134 32555
输出:
same nmbrs: 0
min: 4666 at: 3
max: 40622 at: 2
正确找到了值,但未在第3行中找到。8应该是正确的输出,因为它是包含精确值的行。这是代码的正确版本。问题在于迭代文件行的方式。如果想看到第8行而不是第7行,还需要+1
eqlCounter = 0
octals = []
with open("D:\liczby.txt", "r") as f:
for line in f.readlines():
splited = line.split()
toInt = int(splited[1], 8) #oct to int(dec)
octals.append(toInt)
if int(splited[0]) == toInt:
eqlCounter += 1
# print(splited[0],splited[1],toInt)
low = min(octals)
maxx = max(octals)
print("same nmbrs: ", eqlCounter) #a
print("min: ", min(octals),"at: ",octals.index(low)+1)
print("max: ", max(octals),"at: ",octals.index(maxx)+1)
结果:
same nmbrs: 0
min: 4666 at: 8
max: 47611 at: 1
这是您的代码的正确版本。问题在于迭代文件行的方式。如果想看到第8行而不是第7行,还需要+1
eqlCounter = 0
octals = []
with open("D:\liczby.txt", "r") as f:
for line in f.readlines():
splited = line.split()
toInt = int(splited[1], 8) #oct to int(dec)
octals.append(toInt)
if int(splited[0]) == toInt:
eqlCounter += 1
# print(splited[0],splited[1],toInt)
low = min(octals)
maxx = max(octals)
print("same nmbrs: ", eqlCounter) #a
print("min: ", min(octals),"at: ",octals.index(low)+1)
print("max: ", max(octals),"at: ",octals.index(maxx)+1)
结果:
same nmbrs: 0
min: 4666 at: 8
max: 47611 at: 1
执行代码时,会出现编译错误:
Traceback (most recent call last):
File "app.py", line 5, in <module>
lines = f.readline()
ValueError: Mixing iteration and read methods would lose data
执行代码时,会出现编译错误:
Traceback (most recent call last):
File "app.py", line 5, in <module>
lines = f.readline()
ValueError: Mixing iteration and read methods would lose data
在数据集中输出它不是偶数…它是,只是作为十进制数字打印的程序从十月转换到十二月,然后找到最大值/最小值。例如11072(o)=4666(d)我知道,行不是相关值。在数据集中输出它不是偶数…它是,只是作为十进制数字打印的程序从十月转换到十二月,然后找到最大值/最小值。例如11072(o) =4666(d)我明白了,行不是相关值。