Python 迭代列表时,将该值和接下来的2个值添加到新列表中

Python 迭代列表时,将该值和接下来的2个值添加到新列表中,python,python-3.x,Python,Python 3.x,我目前正在做一个程序来扫描一个PDF文件,并寻找关键字“Ref”。找到这个单词后,我需要取下两个字符串“code”和“shares”,并将它们添加到新列表中,以便稍后导入Excel 我已经编写了从PDF文件中提取文本并将其添加到列表中的代码。然后我遍历这个列表并查找'Ref'关键字。找到第一个后,它会将其添加到列表中,没有问题。然而,当涉及到下一个实例时,它会将Ref+代码和共享的第一个实例再次添加到列表中,而不是PDF文件中的下一个实例 下面是将Ref+code+shares添加到新列表pyt

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

我已经编写了从PDF文件中提取文本并将其添加到列表中的代码。然后我遍历这个列表并查找'Ref'关键字。找到第一个后,它会将其添加到列表中,没有问题。然而,当涉及到下一个实例时,它会将Ref+代码和共享的第一个实例再次添加到列表中,而不是PDF文件中的下一个实例

下面是将Ref+code+shares添加到新列表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','Ref','1','266','Ref','1','266']

正如你所看到的,它每次都是相同的参考号。。。正确的输出应该如下所示:

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

如果有人知道为什么总是添加第一个ref和单词列表中每个ref实例的代码,请告诉我!我被卡住了!谢谢

当您使用list.indexstr函数时,它会返回str的第一次出现。要解决此问题,请按索引进行迭代:

for i in range(len(wordList):
    match = False

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

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

我希望这有帮助。干杯

您的问题是,对wordlist的index方法的调用只会返回它罚款的第一个实例。也就是说,您总是会得到Ref的第一个实例。相反,更好的方法是在列表上使用enumerate,它会在运行时为每个条目提供索引和值,然后您可以只引用索引值来获得接下来的两个元素。下面是代码示例

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)
输出

您还可以清理和删除大量不需要的代码,并将其编写为:

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

您搜索ref的索引位置。根据列表索引方法的文档,这将始终返回ref的第一个匹配项。返回值等于的第一项列表中从零开始的索引x@ChrisDoyle我将如何查找列表中下一个“ref”的索引?最好使用类似于for index的内容,单词列表中的单词:这将为您提供每个单词的索引。您能提供输入吗data@henry434我已经用一个例子补充了一个答案。请根据需要调整,因为你没有提供你的输入数据,所以我不得不对它的外观进行说明
for index, word in enumerate(wordList):
    if word == 'Ref':
        refList += [word, wordList[index+1], wordList[index+2]]