简体   繁体   English

在for循环中使用嵌套的if语句

[英]using a nested if statement within a for loop

i'm trying to read through a string (with no spaces) pull out instances where there is a single lowercase letter surrounded on both sides by 3 upper cases (ie HHSkSIO). 我正在尝试通读一个字符串(无空格),以拔出其中一个小写字母在两侧被3个大写字母包围的实例(即HHSkSIO)。 I've written the code below: 我写了下面的代码:

def window(fseq, window_size=7):
    for i in xrange(len(fseq) - window_size + 1):
        yield fseq[i:i+window_size]


for seq in window('asjdjdfkjdhfkdjhsdfkjsdHJJnJSSsdjkdsad', 7):
    if seq[0].isupper and seq[1].isupper and seq[2].isupper and seq[3].islower and seq[4].isupper and seq[5].isupper and seq[6].isupper:
            print seq

where the first function window allows me to iterate through the string using a sliding window of 7 and the second part, the for statement, checks whether the characters within each window are higher higher higher lower higher higher higher. 其中第一个功能窗口允许我使用滑动窗口7遍历字符串,第二个部分for语句检查每个窗口内的字符是否更高,更高,更高,更高,更高,更高,更高。 When I run the code, it comes out with: 当我运行代码时,它带有:

asjdjdf
sjdjdfk
jdjdfkj
djdfkjd
jdfkjdh
dfkjdhf
fkjdhfk
kjdhfkd
jdhfkdj
dhfkdjh
hfkdjhs
fkdjhsd
kdjhsdf
djhsdfk
jhsdfkj
hsdfkjs
sdfkjsd
dfkjsdH
fkjsdHJ
kjsdHJJ
jsdHJJn
sdHJJnJ
dHJJnJs
HJJnJsd
JJnJsdj
JnJsdjk
nJsdjkd
Jsdjkds
sdjkdsa
djkdsad

How can I make the for statement only print out the sliding window which conforms to the above if statement, rather than printing out all of them? 我怎样才能使for语句打印出符合上述if语句的滑动窗口,而不是全部打印出来? PS i know this is probably a very clunky way of doing it, I'm a beginner and it was the only thing i could think of! 附言:我知道这可能是很笨拙的方式,我是一个初学者,这是我唯一想到的!

You have to call the isupper and islower methods: 您必须调用isupperislower方法:

    if seq[:3].isupper() and seq[3].islower() and seq[4:].isupper():
        print seq

The problem is that you are missing the () in your calls to .isupper, which always evaluate to true. 问题在于,您对.isupper的调用中始终缺少(),该调用始终为true。

Try: 尝试:

def window(fseq, window_size=7):
    for i in range(len(fseq) - window_size + 1):
        yield fseq[i:i+window_size]


for seq in window('asjdjdfkjdhfkdjhsdfkjsdHJJnJSSsdjkdsad', 7):
    if seq[0].isupper() and seq[1].isupper() and seq[2].isupper() and seq[3].islower() and seq[4].isupper() and seq[5].isupper() and seq[6].isupper():
        print (seq)

The other way of doing it, would be: 另一种方法是:

import re
s = re.compile(r'[A-Z]{3}[a-z][A-Z]{3}')
def window(fseq, window_size=7):
    for i in range(len(fseq) - window_size + 1):
        yield fseq[i:i+window_size]

for seq in window('asjdjdfkjdhfkdjhsdfkjsdHJJnJSSsdjkdsad', 7):
    result = s.search(seq)
    if result is not None:
        print(result.group())

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

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