简体   繁体   English

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

[英]Nested "if" statement in for-loop

I am having some difficulty figuring this out.我很难弄清楚这一点。 The question in my assignment asks that we:我作业中的问题要求我们:

Print the elements in the nmrls list that have more than or equal to 7 letters and has either the letter 'o' or the letter 'g'.打印nmrls列表中具有大于或等于 7 个字母且具有字母“o”或字母“g”的元素。

and the results should be three ( eighteen , fourteen and twenty-one ) but I only get twenty-one.结果应该是三个( eighteenfourteentwenty-one ),但我只得到了二十一。

What am I doing wrong?我究竟做错了什么?

Also unrelated question, do we always have to run the entire code every time we open Jupyter notebook (for a sophisticated language it seems very cumbersome)?还有一个不相关的问题,每次打开 Jupyter notebook 时,我们是否总是需要运行整个代码(对于复杂的语言来说似乎很麻烦)?

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)

I suspect that what you need is a loop body that actually checks the word in question:我怀疑您需要的是一个实际检查相关单词的循环体:

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

This occurs because your if statement doesn't actually check if 'o' or 'g' is in the string, but whether 'o' or 'g' exists, due to the inherent true boolean value of non-zero length strings in Python.发生这种情况是因为您的if语句实际上并未检查字符串中是否包含 'o' 或 'g',而是检查是否存在 'o' 或 'g',这是由于 Python 中非零长度字符串固有真布尔值.

I would recommend reimplementing this using len():我建议使用len()重新实现它

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

Something similar could also be achieved using list comprehension:使用列表理解也可以实现类似的东西

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

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

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