2017-04-01 54 views
0

我创建了这个程序,要求将位置列表输入到文件中,而不是将其保存为列表,并将其另存为另一个文件,用户必须输入每个位置具有的单词列表。例如,如果我输入:从位置创建句子时发生逻辑错误

1 2 3 4 5 1 2 3 4 5 

this is a repeated sentence 

的outpur应该

this is a repeated sentence this is a repeated sentence 

然而,当我运行我的代码,我得到的位置的列表,而不是

1 2 3 4 5 1 2 3 4 5 

这里是我的代码:

import subprocess 
process_position = subprocess.Popen(["notepad","list_of_numbers.txt"]) 
process_position.wait() 
positions = [] 
with open("list_of_numbers.txt","r") as f: 
    positions = f.read().split() 

process_words = subprocess.Popen(["notepad","list_of_words.txt"]) 
process_words.wait() 
sentence = "" 
with open("list_of_numbers.txt","r") as s: 
    sentence= s.read().split() 


mapping = {} 

for (position, word) in zip(positions, sentence): 
    mapping[position] = word 


output = [mapping[position] for position in positions] 

print(' '.join(output)) 
+0

嘛'positions'确实含有** **的字符串,而不是** **整数... –

+0

使用'映射[INT(位置)] = word' ... –

+0

我试过,但我得到一个语法错误 –

回答

0

我觉得你很困惑。如果我理解正确的话,position列表就是您要打印的字位置列表。所以,你不想要的话从sentence.

一起zip它相反,只需使用position数的整数值查找词语的sentence列表:

result = [] 
for p in map(int, position): 
    result.append(sentence[p]) 

print(' '.join(result)) 

或者,挤点点:

print(' '.join([sentence[p] for p in map(int, position)])) 
+0

它没有出现错误“列表索引超出范围” –

+0

尝试使用基于0的位置而不是基于1的位置。或者,使用'sentence [p-1]'而不是'sentence [p]'。 –