gpt4 book ai didi

python isinstance in 循环嵌套

转载 作者:行者123 更新时间:2023-12-01 00:17:01 24 4
gpt4 key购买 nike

Python 深入“PyPDF2.generic.Destination”的嵌套列表并列出对象以到达列表的最后一个实例的最有效方法是什么?(获取 PDF 大纲的所有级别及其页码)。

pdfread = p2.PdfFileReader(list_files)
s = pdfread.outlines
chapters = []
pages = []
levels = []
files = []

for x in s:
files.extend([x])
if isinstance(x, (int, list, float, complex)):
for y in x:
if isinstance(y, (int, list, float, complex)):
for z in y:
if isinstance(z, (int, list, float, complex)):
for a in z:
if isinstance(a, (int, list, float, complex)):
for c in a:
if isinstance(c, (int, list, float, complex)):
print(c.title)
else:
chapters.extend([c.title])
pages.extend([pdfread.getDestinationPageNumber(c)])
levels.extend(['5'])

else:
chapters.extend([a.title])
pages.extend([pdfread.getDestinationPageNumber(a)])
levels.extend(['4'])

else:
chapters.extend([z.title])
levels.extend(['3'])
pages.extend([pdfread.getDestinationPageNumber(z)])
else:
chapters.extend([y.title])
levels.extend(['2'])
pages.extend([pdfread.getDestinationPageNumber(y)])
else:
chapters.extend([x.title])
levels.extend(['1'])
pages.extend([pdfread.getDestinationPageNumber(x)])

df = pd.DataFrame({'chapters': chapters, 'pages' : pages, 'levels' : levels})
df.head(44)

最佳答案

只需定义一个递归函数:

def nested_is_instance_check(s, level, pages):
level +=1
if isinstance(x, (int, list, float, complex)):
for x in s:
nested_is_instance_check(s, level, pages)
else:
chapters.extend([y.title])
levels.extend(['level'])
pages.extend([pdfread.getDestinationPageNumber(s)])

nested_is_instance_check 为文件中的每个级别调用自身。

关于python isinstance in 循环嵌套,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59262016/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com