将值与列表中的多个值进行比较

时间:2018-03-05 01:11:57

标签: python python-3.x list

我遇到此代码的问题:

words = []
counter = 0
wordcount = 0
intraWord = 1
loop = 0
ConsonantCluster3 = ["sch" "scr", "shr", "sph", "spl", "spr", "squ", "str", "thr"]
while(loop == 0):
    sentence = input('Enter a sentence in english: ')
    sentence.lower()
    words = sentence.split()
    for x in range(0,intraWord):
        if(words[counter][:3] in ConsonantCluster3):
            print("True")
            input()
        else:
            print("False")
            input()

我的目标是,例如,如果用户输入“屏幕”,程序将吐出True,而是吐出False。我使用的是Python 3。

2 个答案:

答案 0 :(得分:0)

这是一种方式。

ConsonantCluster3 = {"sch", "scr", "shr", "sph", "spl", "spr", "squ", "str", "thr"}

sentence = input('Enter a sentence in english: ')
words = sentence.lower().split()

for x in words:
    if x[:3] in ConsonantCluster3:
        print("True")
    else:
        print("False")

<强>解释

  • 您的许多变量和循环都不是必需的。
  • 在第一个元素之后,您的列表缺少,
  • 您只需通过for x in lst
  • 循环浏览列表
  • str.lower()不在原位。分配给变量。

答案 1 :(得分:0)

您还可以使用列表推导来组合条件以使代码更简单:

ConsonantCluster3 = {"sch", "scr", "shr", "sph", "spl", "spr", "squ", "str", "thr"}

sentence = input('Enter a sentence in english: ')
words = sentence.lower().split()

if len([x for x in words if x[:3] in ConsonantCluster3]) > 0:
    print("True")
else:
    print("False")