Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在不覆盖列表的情况下将列表中的特定元素转换为另一个列表?(索引器:列表索引超出范围)_Python_Loops_Nested - Fatal编程技术网

Python 如何在不覆盖列表的情况下将列表中的特定元素转换为另一个列表?(索引器:列表索引超出范围)

Python 如何在不覆盖列表的情况下将列表中的特定元素转换为另一个列表?(索引器:列表索引超出范围),python,loops,nested,Python,Loops,Nested,我正在编写一个代码,该代码使用嵌套循环从文本文件读取列表。现在,它通过输入的文件路径进入一个文件,然后打开该文件并将其中的所有内容转换为列表。这很好用 然而,在它再次循环并对其余输入的文件执行相同操作之前,我希望它自动从每个列表的最后一个元素中提取第六个元素,并将其放入另一个列表中,而不覆盖任何内容。这就是我到目前为止所做的: listpath = "/Users/myname/Documents/list.txt" lstfull = [] lstreduced = [] with ope

我正在编写一个代码,该代码使用嵌套循环从文本文件读取列表。现在,它通过输入的文件路径进入一个文件,然后打开该文件并将其中的所有内容转换为列表。这很好用

然而,在它再次循环并对其余输入的文件执行相同操作之前,我希望它自动从每个列表的最后一个元素中提取第六个元素,并将其放入另一个列表中,而不覆盖任何内容。这就是我到目前为止所做的:

listpath = "/Users/myname/Documents/list.txt"
lstfull = []
lstreduced = []


with open(listpath, "r") as flp:
    file_list = flp.readlines() #Makes a list from the file paths 
    fp = [x.strip() for x in file_list] #comprehension that removes \n from strings
    for i in fp: #list of file paths
        with open(i, "r") as f: #Opens each file from the file path
            for line in f:
                lstfull.append(line) #Takes each line and appends it to the list (lst)
                six = len(lstfull) - 6 #This is the element from each of the files I want
                lstreduced.append(lstfull[six])
txt只是一个文本文件,其中包含一个文件路径列表,我可以输入这些路径,这样代码就可以在任何地方运行

最后一行(lstredured.append(lstfull[si])是我遇到问题的地方。
我只希望列表由每个输入列表中倒数第六个元素组成,但我得到了错误:Indexer:列表索引超出范围。有人知道如何解决此问题吗?

可以使用

lstfull[-6]
只要每个列表至少有6个元素,就应该避免索引器

您的代码可能有缩进错误吗?如果您执行以下操作,则更有意义:

with open(listpath, "r") as flp:
    file_list = flp.readlines() #Makes a list from the file paths 
    fp = [x.strip() for x in file_list] #comprehension that removes \n from strings
    for i in fp: #list of file paths
        with open(i, "r") as f: #Opens each file from the file path
            for line in f:
                lstfull.append(line) #Takes each line and appends it to the list (lst)
            lstreduced.append(lstfull[-6])

谢谢你,这是正确的,我的代码现在正在运行,你是最好的