gpt4 book ai didi

python - 更改字符串列表中的字符串

转载 作者:太空宇宙 更新时间:2023-11-03 17:35:49 25 4
gpt4 key购买 nike

所以基本上我有一个巨大的字符串列表,例如

list = ["hello", "my", "name", "is"] 

等等...

我想问用户一个问题,如果用户用我列表中的单词进行回答,我想将其替换为"is"。我该怎么办,我尝试过的一切都失败了。谢谢!

最佳答案

列表理解:

# user input in user_input
new_list = [item if item != user_input else "yes" for item in old_list]

这会将与 user_input 相同的任何内容替换为“yes”。

提示:不要隐藏内置 list .

输出:

>>> old_list = ["hello", "my", "name", "is"] 
>>> user_input = "hello"
>>> new_list = [item if item != user_input else "yes" for item in old_list]
>>> new_list
['yes', 'my', 'name', 'is']

关于python - 更改字符串列表中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31212249/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com