微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python 3.7 else 语句没有显示正确的索引?

如何解决Python 3.7 else 语句没有显示正确的索引?

我的目标是将文本文件中的行打印在一起。然而,有些线条并没有像它们应该的那样在一起。我解决了分母在后面的第一个问题。对于 processListObservable 语句,它们似乎都具有相同的值/索引。

else

终端输出

import fitz  # this is pymupdf

with fitz.open("math-problems.pdf") as doc: #below converts pdf to txt
    text = ""
    for page in doc:
        text += page.getText()

file_w = open("output.txt","w") #save as txt file
file_w.write(text)
file_w.close()

file_r = open("output.txt","r") #read txt file
word = 'f(x) = '

#--------------------------
list1 = file_r.readlines()  # read each line and put into list

list2 = [k for k in list1 if word in k] # look for all elements with "f(x)" and put all in new list

list1_N = list1
list2_N = list2
list1 = [e[3:] for e in list1] #remove first three characters (the first three characters are always "1) " or "A) "

char = str('\n')

for char in list2:
    index = list1.index(char)
    def digitcheck(s):
        isdigit = str.isdigit
        return any(map(isdigit,s))
    xx = digitcheck(list1[index])
    if xx:
        print(list1[index] + " / " + list1_N[index+1])
    else:
        print(list1[index] + list1[index+1]) # PROBLEM IS HERE,HOW COME EACH VALUE IS SAME HERE?


解决方法

已解决 @copperfield 是正确的,我有重复的值,所以我的索引是重复的。我在 here 中使用 @Shonu93 的解决方案解决了这个问题。本质上,它定位所有重复值的索引,并将这些索引放入一个列表 elem_pos,然后从 list1

打印每个索引
if empty in list1:
counter = 0
elem_pos = []
for i in list1:
    if i == empty:
        elem_pos.append(counter)
    counter = counter + 1
xy = elem_pos

for i in xy:
print(list1[i] + list1_N[i+1])

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。