繁体   English   中英

python用word替换位置

[英]python replacing position with word

我试图编写一个程序,要求用户输入一个位置列表,然后为每个位置输入(按顺序)一个单词,然后用该单词创建一个句子,但是我不知道如何将2个输入连接在一起以形成表格一句话

例如,如果我输入职位:

1 2 3 4 5 1 2 3 4 5

然后输入以下内容:

 This is a repeated sentence

输出应为:

This is a repeated sentence This is a repeated sentence

到目前为止,我只知道如何使用户编写位置列表和类似这样的单词:

import subprocess
subprocess.Popen(["notepad","list_of_numbers.txt"])
subprocess.Popen(["notepad","list_of_words.txt"])

但我不知道如何连接2列表。 有人可以帮我吗?

使用join()和split()

a = 'This is a repeated sentence'
b = a.split()
po = [1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
" ".join(b[i-1] for i in po)

结果是

'This is a repeated sentence This is a repeated sentence'

假设您有两个列表

positions = [1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
sentence = "This is a repeated sentence"

// create a mapping between positions and words
mapping = {}

words = sentence.split()

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

// output according to the lists of positions
output = [mapping[position] for position in positions]

print(' '.join(output))

输出:

This is a repeated sentence This is a repeated sentence

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM