列表索引:检查列表是否包含关键字

问题描述 投票:-1回答:2

我已经编写了代码来检查输入的答案,以查看它是否包含列表中的关键字。

我当前的代码是:

list = ["cool", "yes", "positive", "yeah", "maybe", "possibly"]
a = input ("Input a keyword:")
for item in list:
    if item in a:
        if item in list[0:3]:
            print ("you inputted cool or yes or positive")
        else:
            print ("You inputted yeah or maybe or possibly")

这是我遇到的问题if item in list[0:3]:。如果您输入的第一个关键字的索引为0(很酷),则该程序有效,但是如果您输入“是”或“正”,则不执行任何操作。

为什么这么做?我知道我做错了事,但是与Python中的列表和元组的交互很少,因此我对它们的了解不多。

python python-3.x list conditional-statements python-3.4
2个回答
0
投票

虽然您的代码有效,但是可以通过检查原始关键字列表的elif[3:]语句来进行改进,如下所示:

k = ["cool", "yes", "positive", "yeah", "maybe", "possibly"]
m = input ("Input a keyword:")
for i in k:
    if i in m:
        if i in k[:3]:
            print ("you inputted cool or yes or positive")
        elif i in k[3:]:
            print ("You inputted yeah or maybe or possibly")
        else:
            print ("You inputted a word not in the keyword list")

允许您使用第三条print()语句捕获输入关键字中没有关键字的情况。

您当然可以通过拆分输入消息来反转比较逻辑。拆分输入消息,因为您无法控制在第一个位置中输入了多少个单词,如下所示:

k = ["cool", "yes", "positive", "yeah", "maybe", "possibly"]
m = input ("Input a keyword:")

for i in m.split():
    if i in k[:3]:
        print ("you inputted cool or yes or positive")
    elif i in k[3:]:
        print ("You inputted yeah or maybe or possibly")
    else:
        print ("You inputted a word not in the keyword list") 

如果关键字列表大于平均输入消息,则后一个示例可能更经济,因为它只需要遍历输入消息中的单词数即可。如果输入消息中有两个单词,两个单词都在关键字列表中,则也会选择此选项。

我对您的其他问题here: How to use lists in conditionals给出了类似的答案


-2
投票

只需尝试raw_input()

A = raw_input ("Input a keyword:")
© www.soinside.com 2019 - 2024. All rights reserved.