繁体   English   中英

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

[英]Comparing a value to multiple values in a 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。

这是一种方法。

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()不在位。 分配给变量。

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

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")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM