下面的re.findall()代码有什么错误?

时间:2017-08-30 17:46:43

标签: regex python-3.x

import re
for test in range(int(input())):
    a = input()                  # input a string
    n = a.replace("=", "")       # if string contains '='then remove it
    gg = re.findall(r ">+", n)   # count >
    l1 = len(max(gg, key = len)) # count consecutive >
    hh = re.findall(r "<+", n)   # count <
    l2 = len(max(hh, key = len)) # count consecutive <
    print(max(l1, l2) + 1)       # print max of two + 1

输入是:
4
&LT;&LT;&LT;
&LT;&GT;&LT;
&LT; =&GT;
&LT; =&LT;
如果我运行上面的代码,我遇到一个错误。我在SO上读它只是语法仍然是我收到错误:

Traceback (most recent call last):<br/>   File "/home/fea0d5e04ac92cb3a1e4f041940f2dfc.py", line 8, in <module><br/>
l2=len(max(hh, key=len))<br/> ValueError: max() arg is an empty sequence

1 个答案:

答案 0 :(得分:0)

max在空序列上失败。

Python&gt; = 3.4

max采用可选的默认参数:

l1 = len(max(gg, key = len, default=0)) # count consecutive >

Python&lt; 3.4

添加警卫以检查列表是否为空

if len(hh) > 0: 
    l2 = len(max(hh, key = len)) # count consecutive <
else:
    l2 = 0