簡體   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