在for循环中嵌套“ if”语句

时间:2020-10-16 22:56:12

标签: python python-3.x

我很难弄清楚这一点。我的作业中的问题要求我们:

打印nmrls列表中具有7个以上字母且具有字母'o'或字母'g'的元素。

结果应该是三个(eighteenfourteentwenty-one),但我只有21个。

我在做什么错了?

还有一个不相关的问题,我们每次打开Jupyter笔记本时是否都必须始终运行整个代码(对于复杂的语言来说似乎很麻烦)?

nmrls = inflect.engine()
x=[]
for i in range (0,22):
    x.append(nmrls.number_to_words(i))   
for nmrls in x:
    count=0
    for letter in nmrls:
        count+=1
        if count>=7 and "o"  or "g" :   
            print(nmrls)

2 个答案:

答案 0 :(得分:2)

我怀疑您需要的是一个循环主体,该循环主体实际上检查了有问题的单词:

for word in x:
    if len(word) >= 7 and ('o' in word or 'g' in word):
        ...

答案 1 :(得分:2)

之所以会这样,是因为inherent true boolean value of non-zero length strings导致您的if语句实际上并不检查字符串中是否包含“ o”或“ g”,而是存在“ o”或“ g”在Python中。

我建议使用len():

重新实现
for nmrls in x:
    if len(nmrls) >= 7 and ('o' in nmrls or 'g' in nmrls):
        print(nmrls)

使用list comprehension:

也可以实现类似的目的
x = [word for word in x if len(word) >= 7 and ('o' in word or 'g' in word)]