File "log1.py", line 140
for ref, occurnum in nsmallest(10, d.iteritems(), key=lambda (k,v): (-v,k)):
^
SyntaxError: invalid syntax
程式碼如下
def TopOccurr(num, request, total):
args = parse_args()
d = {}
for i in get_obj[num]:
if i in d:
d[i] = d[i]+1
else:
d[i] = 1
x = PrettyTable([request, total])
x.align["Requests"] = "l"
x.padding_width = 1
for ref, occurnum in nsmallest(10, d.iteritems(), key=lambda (k,v): (-v,k)):
x.add_row([ref[:120], occurnum])
return x.get_string(start=0, end=10, sortby=total, reversesort=True)
py3.5.2
高洛峰2017-05-18 11:04:03
lambda定義的時候,如果有多個參數,那麼這些參數是不需要加括號的
e.g.
l=lambda x,y:(y,x) # 正确
l=lambda (x,y):(y,x) # 报错
官方文件中的lambda:
貼上修改後完整程式碼:
def TopOccurr(num, request, total):
args = parse_args()
d = {}
for i in get_obj[num]:
if i in d:
d[i] = d[i]+1
else:
d[i] = 1
x = PrettyTable([request, total])
x.align["Requests"] = "l"
x.padding_width = 1
for ref, occurnum in nsmallest(10, d.iteritems(), key=lambda k,v:(-v,k)):
x.add_row([ref[:120], occurnum])
return x.get_string(start=0, end=10, sortby=total, reversesort=True)
實測沒有錯誤(Python 3.6.0,IPython 5.3.0)