"Not In" If statement not operating correctly 不正确运行的"If"语句

2024-04-29 04:05:42 发布

您现在位置:Python中文网/ 问答频道 /正文

if ('SCT', 'OVC', 'CLR') not in words[i]:
   list_stat.append(words[i])
       i=i+1
       print words[i]
   else:
       i=i+1    

我试图用Python创建一个or语句来解析一个列表。关键字的数目比if语句中的三个要长得多,所以嵌套的if语句很快就会变得多余。我对Python有点陌生,但是not in语句似乎是将所有关键字组合在一起的最有效的方法。问题是,我在尝试将元组与数组进行比较时不断出错。我也这样试过:

if words[i] not in ('SCT', 'OVC', 'CLR'):
   list_stat.append(words[i])
        i=i+1
        print words[i]
   else:
        i=i+1

两者都不能正常工作。我还应该提到,第二种方法运行时没有错误,但不会从我的列表中删除单词。这三个词在我的列表中出现过多次,尽管not-in语句的目的就是要去掉它们。我正在努力摆脱这些词的所有个别实例。我也尝试过{}而不是(),但两者都不能去掉列表中的单个单词。你知道我做错了什么吗?你知道吗


Tags: in列表ifnot关键字语句elsestat
3条回答
list_stat.append([x for x in words if x not in ('SCT', 'OVC', 'CLR')])

“列出words中的每个单词,前提是它不在('SCT', 'OVC', 'CLR')中。将此新列表附加到list_stat

这些错误可能是由于缩进错误造成的。除此之外,您还可以使用^{}循环来简化事情(它将为您完成i=i+1):

for i in range(len(words)):
    if words[i] not in ['SCT', 'OVC', 'CLR']:
        list_stat.append(words[i])
        print words[i]

doesn't remove the words from my list

无论哪种方式,都是填充新列表(list_stat),而不是从words中删除。你知道吗

您没有解释您的用户到底想做什么,但它看起来像是在实现set操作—这些操作在python中有本机实现

见:https://docs.python.org/2/library/sets.html

具体来说:

if set(['SCT', 'OVC', 'CLR']) & words[i] # intersection is not empty - one of the words is in words[i]
...

相关问题 更多 >