1

我有一个像这样的大文本文件(单词之间没有空格,但每行中的每个单词):

this

is

my

text

and

it

should

be

awesome

.

我也有一个这样的列表:

index_list = [[1,2,3,4,5],[6,7,8][9,10]]

现在我想用我的文本文件的相应索引行替换每个列表的每个元素,所以预期的答案是:

new_list = [[this, is, my, text, and],[it, should, be],[awesome, .]

我尝试了一个令人讨厌的解决方法,两个 for 循环的范围函数太复杂了(所以我想)。然后我尝试了它linecache.getline,但这也有一些问题:

import linecache

new_list = []

for l in index_list:
       for j in l:
             new_list.append(linecache.getline('text_list', j))

这确实只产生了一个我不想要的大列表。此外,在每个单词之后,我都会遇到一个不好的问题\n,当我打开文件时我没有得到,b = open('text_list', 'r').read.splitlines()但我不知道如何在我的替换函数(或创建,而是)中实现它,所以我没有得到[['this\n' ,'is\n' , etc...

4

2 回答 2

1

你很亲密。只需使用临时列表并将其附加到主列表即可。您也可以使用str.strip删除换行符。

前任:

import linecache

new_list = []
index_list = [[1,2,3,4,5],[6,7,8],[9,10]]
for l in index_list:
    temp = []   #Temp List
    for j in l:
        temp.append(linecache.getline('text_list', j).strip())
    new_list.append(temp)       #Append to main list. 
于 2019-06-11T13:25:59.463 回答
0

iter只要您拥有text_listsum(map(len, index_list))

text_list = ['this', 'is', 'my', 'text', 'and', 'it', 'should', 'be', 'awesome', '.']

index_list = [[1,2,3,4,5],[6,7,8],[9,10]]
text_list_iter = iter(text_list)
texts = [[next(text_list_iter) for _ in index] for index in index_list]

输出

[['this', 'is', 'my', 'text', 'and'], ['it', 'should', 'be'], ['awesome', '.']]

但我不确定这是否是你想要做的。也许我假设 index_list 的某种排序。我能想到的另一个答案是这个列表理解

texts_ = [[text_list[i-1] for i in l] for l in index_list]

输出

[['this', 'is', 'my', 'text', 'and'], ['it', 'should', 'be'], ['awesome', '.']]
于 2019-06-11T13:28:55.087 回答