search

Home  >  Q&A  >  body text

python - What is the error in this sentence?

  File "log1.py", line 140
    for ref, occurnum in nsmallest(10, d.iteritems(), key=lambda (k,v): (-v,k)):
                                                                 ^
SyntaxError: invalid syntax

code show as below


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

天蓬老师天蓬老师2794 days ago621

reply all(3)I'll reply

  • 高洛峰

    高洛峰2017-05-18 11:04:03

    When defining lambda, if there are multiple parameters, these parameters do not need to be bracketed
    e.g.

    l=lambda x,y:(y,x) # 正确
    l=lambda (x,y):(y,x) # 报错

    lambda in official documentation:

    Post the modified complete code:

    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)

    No errors reported in actual testing (Python 3.6.0, IPython 5.3.0)

    reply
    0
  • 漂亮男人

    漂亮男人2017-05-18 11:04:03

    Lambda in python3 does not support decompressing data using parentheses

    reply
    0
  • PHP中文网

    PHP中文网2017-05-18 11:04:03

    Just remove the parentheses of the parameters.

    reply
    0
  • Cancelreply