简体   繁体   English

python用word替换位置

[英]python replacing position with word

I was trying to code a program that asks a user to enter a list of positions and then enter (in order) a word for each position and create a sentence with the word but im i dont know how to connect the 2 inputs together to form a sentence 我试图编写一个程序,要求用户输入一个位置列表,然后为每个位置输入(按顺序)一个单词,然后用该单词创建一个句子,但是我不知道如何将2个输入连接在一起以形成表格一句话

for example if i enter the position: 例如,如果我输入职位:

1 2 3 4 5 1 2 3 4 5

and then i enter the words: 然后输入以下内容:

 This is a repeated sentence

the output should be: 输出应为:

This is a repeated sentence This is a repeated sentence

So far i only know how to make the user write the list of position and the words like this: 到目前为止,我只知道如何使用户编写位置列表和类似这样的单词:

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

but i dont know how to connected the 2 list. 但我不知道如何连接2列表。 could somebody help me? 有人可以帮我吗?

use join() and split() 使用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)

results in 结果是

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

Suppose you got the two lists 假设您有两个列表

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))

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