简体   繁体   中英

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

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. could somebody help me?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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