python中的len(list)返回1而不是0

Nic*_*las 0 python glassfish-3

我们正试图计算玻璃鱼中的实例.当使用len()函数时,它总是返回1而不是0.也许它用空格或其他东西填充列表[0].这是我们的代码.

    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(self.get('hostname'),int(self.get('port')),self.get('username'),allow_agent=True)
    #try:
    stdin, stdout, stderr = ssh.exec_command('~/glassfish3/glassfish/bin/asadmin list-instances')
    result = stdout.readlines()
    #except Exception, e:
    #   return MonitoringResult(MonitoringResult.OK,'all instances up!')
    result = "".join(result)
    #line = re.compile(r'\bnot\s\D*\n')

    #rline = "".join(line.findall((result)))
    line2=re.compile(r'\bnot')
    rline2 = ";".join(line2.findall((result)))
    print(rline2)
    i = 0
    listr = rline2.split(";")

    while(i < (len(listr)):
        i+=1
    print(i)

    if rline2:
        return MonitoringResult(MonitoringResult.CRITICAL,'instance down')
    else:
        return MonitoringResult(MonitoringResult.OK, 'All instances are up')
Run Code Online (Sandbox Code Playgroud)

Bak*_*riu 6

结果str.split 不能为list:

>>> ''.split(';')
['']
Run Code Online (Sandbox Code Playgroud)

如果要检查获取的列表是否包含any非空字符串,请使用any:

>>> any(''.split(';'))
False
>>> any('a;'.split(';'))
True
>>> ';'.split(';')
['', '']
>>> any(';'.split(';'))
False
Run Code Online (Sandbox Code Playgroud)

如果要filter删除空字符串,请使用filter:

>>> filter(None, ';'.split(';'))
[]
Run Code Online (Sandbox Code Playgroud)

或列表理解:

>>> [s for s in ';'.split(';') if s]
[]
Run Code Online (Sandbox Code Playgroud)

我刚刚意识到str.split 可以返回一个空列表.但只有在没有参数的情况下调用:

>>> ''.split()
[]
>>> '    '.split()   #white space string
[]
Run Code Online (Sandbox Code Playgroud)

解释在文档中:

S.split([sep [,maxsplit]]) -> list of strings

S使用sep分隔符字符串返回字符串中单词的列表.如果maxsplit给出,则最多maxsplit完成拆分.如果sep未指定或是None,则任何空格字符串都是分隔符,并从结果中删除空字符串.