繁体   English   中英

将列表中的随机元素与 Python 中的用户输入连接起来

[英]Concatenate random element from list with user input in Python

我正在编写一个代码,允许用户输入他们去过的城市。 用户输入后,我希望我的代码从我的列表中返回一个随机生成的关于城市的评论。 但是,每当我运行代码时,它都会将用户输入与一个随机字母连接起来,这不是我的代码意图。

import random

message = "Type your city here: "

#Comments to concatenate with user input
comments = [f"what a lovely {}", f"I always wanted to visit {}", "I hope you enjoyed your trip to {}"]

#While loop for user input
while True:
   message = input(message)

   for elem in comments:
      message += random.choice(elem)

   if message == "quit":
      break

我想这就是你要找的东西?

import random
#Comments to concatenate with user input 
comments = ["what a lovely ", "I always wanted to visit ", "I hope you enjoyed your trip to "]

#While loop for user input
message = None
while message != "quit":
   message = input("Type your city here: ")
   print(random.choice(comments)+message)

我建议编写一个 function ,它将城市作为输入,然后在最后返回列表。 像这样

def random_quote(city):
    comments = [f"what a lovely ", f"I always wanted to visit ", "I hope you 
     enjoyed your trip to "]
    comment = random.choice(comments)
    return comment + city

random.choice()接受一个列表(查看文档),不要遍历您的comments变量,将其传递给random.choice()并且不要忘记将{}替换为城市:

city = input('Please enter a city')

comment = random.choice(comments)

comment.replace('{}', city)

print(comment)

您不需要在 while 中使用 for 循环。 您应该始终避免while True因为它是错误的开口。 在循环内有一个break通常标志着糟糕的编程。

您可能应该在使用f-string的内容,您似乎也不知道random.choice的作用,因为您将它放入 for which 给了它消息,它随机从中取出一个字符.

import random


def main():
    prompt = "Type your city here: "

    # Comments to concatenate with user input
    comments = ["what a lovely ", "I always wanted to visit ", "I hope you enjoyed your trip to "]

    usr_input = input(prompt)
    # While loop for user input
    while usr_input != 'quit':
        message = random.choice(comments) + usr_input
        usr_input = input(prompt)


if __name__ == '__main__':
    main()

暂无
暂无

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

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