Python строка заменяется случайным образом - PullRequest
1 голос
/ 31 января 2020

Меня интересует python, его простота, удобочитаемость и гибкость. И я хочу заменить строку случайным образом. Я имею в виду

animals = ["cat", "dog", "monkey", "tiger"]

template = "$animal fights with $animal. $animal can play with $animal. Sth $animal sth $animal ..."

Я хочу заменить $animal случайно выбранным элементом в animals в каждом случае. Например, я хочу вывести "dog fights with cat. cat can play with tiger. Sth monkey sth dog ...", как это. Конечно, это можно решить с помощью скучного кода. Но есть ли однострочный код " Pythoni c"?

Ответы [ 4 ]

4 голосов
/ 31 января 2020

Я бы предпочел что-то подобное для простых случаев:

import random

animals = ["cat", "dog", "monkey", "tiger"]


def ra():
    return random.choice(animals)


print(f'{ra()} fights with {ra()}. {ra()} can play with {ra()}. Sth {ra()} sth {ra()} ...')

Но это ближе к вашей отправной точке, вы можете предпочесть это:

import re
import random

animals = ["cat", "dog", "monkey", "tiger"]
template = "$animal fights with $animal. $animal can play with $animal. Sth $animal sth $animal ..."

print(re.sub(r'\$animal', lambda _: random.choice(animals), template))

Обратите внимание, что оба решения не волнует, сколько животных вы заменяете.

1 голос
/ 31 января 2020

Попробуйте использовать random.shuffle() и .format() вот так

template = '{} fights with {}. {} can play with {}. Sth {} sth {}'.format(random.choice(animals), random.choice(animals), random.choice(animals), random.choice(animals), random.choice(animals), random.choice(animals))
0 голосов
/ 31 января 2020

Вы можете использовать str.split():

from random import choice

res = "".join(s + choice(animals) for s in template.split("$animal")[:-1]) + template.rsplit("$animal", 1)[1]
0 голосов
/ 31 января 2020
import random

animals = ["cat", "dog", "monkey", "tiger"]

template = "random.choice(animals) fights with random.choice(animal). random.choice(animal) can play with random.choice(animal). Sth random.choice(animal) sth random.choice(animal) ..."
...