首页 > 解决方案 > 在迭代列表时,将值和接下来的 2 个值添加到新列表中

问题描述

我目前正在制作一个程序来扫描 PDF 文件并查找关键字“Ref”。一旦找到这个词,我需要获取接下来的两个字符串,“code”和“shares”,并将它们添加到一个新列表中,以便稍后导入 Excel。

我编写了代码以从 PDF 文件中获取文本并将其添加到列表中。然后,我遍历此列表并查找“Ref”关键字。当找到第一个时,它将它添加到列表中没有问题。但是,当涉及到下一个时,它将 Ref 的第一个实例(+代码和共享)再次添加到列表中,而不是 PDF 文件中的下一个...

这是将 Ref + code + share 添加到新列表(python 3)的代码:

for word in wordList:
    match = 'false'

    if word == 'Ref':
        match = 'true'
        ref = word
        code = wordList[wordList.index(ref)+1]
        shares = wordList[wordList.index(ref)+2]

    if match == 'true':
        refList.append(ref)
        refList.append(code)
        refList.append(shares)

这是输出:

['Ref','1','266','Ref','1','266','Ref','1','266','Ref','1','266','参考','1','266','参考','1','266']

正如您所看到的,它每次都具有相同的参考编号......正确的输出应该是这样的:

['Ref','1','266','Ref','2','642','Ref','3','435','Ref','4','6763']等...

如果有人知道为什么它总是在 wordList 中的每个“Ref”实例中添加第一个 ref 和代码,请告诉我!我很卡住!谢谢

标签: pythonpython-3.x

解决方案


您的问题是,对 wordlist 的 index 方法的调用只会返回您可以处理的第一个实例。IE 你总是会得到“Ref”的第一个实例。相反,更好的方法是在列表上使用枚举,这将在您进行时为每个条目提供索引和值,然后您可以只引用索引值来获取接下来的两个元素。下面是代码示例。

data = """
this
Ref
1
266
that
hello
Ref
2
642"""

refList = []
wordList = [item.rstrip() for item in data.splitlines()]
for index, word in enumerate(wordList):
    match = 'false'

    if word == 'Ref':
        match = 'true'
        ref = word
        code = wordList[index+1]
        shares = wordList[index+2]

    if match == 'true':
        refList.append(ref)
        refList.append(code)
        refList.append(shares)
print(refList)

输出

['Ref', '1', '266', 'Ref', '2', '642']

您还可以清理并删除许多不需要的代码,然后将其编写为:

for index, word in enumerate(wordList):
    if word == 'Ref':
        refList += [word, wordList[index+1], wordList[index+2]]

推荐阅读