【问题标题】:How to append user input to an item in a list in Python3如何将用户输入附加到 Python3 列表中的项目
【发布时间】:2019-01-14 22:38:22
【问题描述】:

我希望将用户输入连接到现有列表中的项目

我尝试使用 %s 格式化列表中的字符串

from random import randint
user_name = input("Name: ")

我希望 %s 是用户输入的名称

my_list = ["Hello %s, nice to meet u",  
        "%s! what a wonderful name",
        "welcome %s"]
for m in my_list:
    print(randint(my_list)% user_name)

我的输出应该是列表中伴随用户输入的任何项目,即 输出: #你好迈克,很高兴认识你

其中“Mike”是用户输入

【问题讨论】:

  • 你认为randint(my_list) 是做什么的?您应该尝试使用 random 模块中的 choice

标签: python python-3.x list append


【解决方案1】:

我不确定您的代码展示的逻辑是什么,但是,这是我对您想要做的事情的解释。

from random import randint

user_name = input("Name: ")

my_list = ["Hello %s, nice to meet u",
        "%s! what a wonderful name",
        "welcome %s"]

print(choice(my_list) % user_name)

这将打印列表中的一项(随机),并将输入附加到所需位置。

例子:

Name: Tim
Hello Tim, nice to meet u

Name: Pam
Pam! what a wonderful name

Name: Jen
welcome Jen

编辑

使用choice 而不是randint 以清晰/方便/等等。

【讨论】:

  • 非常感谢@TimKlein
【解决方案2】:

我更习惯使用长格式字符串。

from random import choice
user_name = input("Name: ")
my_list = ["Hello {name}, nice to meet u",  
        "{name}! what a wonderful name",
        "welcome {name}"]
for m in my_list:
    print(choice(my_list).format(name=user_name))

但是将您的 randint 更改为 choice 也应该适用于您的情况。

  • randint 返回一个介于 min 和 max 之间的随机数
  • choice随机选择列表中的一个元素

【讨论】:

  • @fill_J 如果对您有帮助,请确保选择此作为正确答案。
【解决方案3】:

我认为其他答案更好,但我做了同样的事情,将列表转换为字符串,然后再转换为列表。

from random import randint
user_name = input("Name: ")

my_list = ["Hello %s, nice to meet u",  "%s! what a wonderful name", "welcome %s"]

# convert/flatten the list to string
list_to_string =  "::".join(str(x) for x in my_list)

# Replace %s with the username
replaced_string = list_to_string.replace("%s",user_name )

# convert string to list 
string_to_list = replaced_string.split("::")

print(string_to_list)

【讨论】:

  • 什么是OP在里面添加一个带有::的字符串?这听起来像是一种危险的方法。至少,使用 list comphrensions 来做类似[s.replace("%s", user_name) for s in my_list]
  • :: 只是一个占位符,因此我可以将string 转换回list。但是,通过计算,您的答案要好得多。
猜你喜欢
  • 2021-03-09
  • 1970-01-01
  • 2013-12-24
  • 1970-01-01
  • 2018-02-09
  • 1970-01-01
  • 2019-04-12
  • 2023-03-25
  • 1970-01-01
相关资源
最近更新 更多