用文本文件中的相应行替换列表列表中的数字

时间:2019-06-11 13:18:07

标签: python python-2.7 linecache

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

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()打开文件时却没有得到,但是我不知道如何在我的replace函数中实现(或者创建)所以我不会得到[['this\n' ,'is\n' , etc...

2 个答案:

答案 0 :(得分: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. 

答案 1 :(得分:0)

只要您SELECT * FROM DBO.TEST(1+1) 具有与SELECT * FROM DBO.TEST((1+1)) 一样多的元素,就可以使用iter进行操作

text_list

输出

sum(map(len, index_list))

但是我不确定这是否是您想要的。也许我假设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', '.']]
相关问题