gpt4 book ai didi

python - 避免打印列表中的某个单词

转载 作者:行者123 更新时间:2023-12-01 05:31:45 25 4
gpt4 key购买 nike

所以我刚刚开始学习Python。我正在做这个练习,要求以下内容:

“实现一个程序,向用户请求单词列表,然后打印列表中的每个非“ secret ”单词。”

这是我到目前为止所拥有的,但在执行代码时它似乎不起作用。有人有什么想法吗?

wordinput = input('Enter a list of words: ')

def keep_secret(l: wordinput) -> list:
for i in wordinput:
if i == 'secret':
return None
else:
print (i)

最佳答案

我认为你正在尝试这样做

wordinput = input('Enter a list of words: ').split()

def keep_secret(l: wordinput) -> list:
for i in wordinput:
if i == 'secret':
continue
else:
print (i)

你可以简化成这样

def keep_secret(l: wordinput) -> list:
for i in wordinput:
if i != 'secret':
print (i)

或者像这样返回过滤后的列表

def keep_secret(l: wordinput) -> list:
return [i for i in wordinput if i != 'secret']

print(keep_secret(wordinput))

关于python - 避免打印列表中的某个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20062870/

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