suchen

Heim  >  Fragen und Antworten  >  Hauptteil

python – Was ist an diesem Satz falsch?

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

Der Code lautet wie folgt


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

天蓬老师天蓬老师2755 Tage vor593

Antworte allen(3)Ich werde antworten

  • 高洛峰

    高洛峰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)

    Antwort
    0
  • 漂亮男人

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

    python3中lambda不支持用括号的方式解压数据

    Antwort
    0
  • PHP中文网

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

    把参数的括号去掉就行了。

    Antwort
    0
  • StornierenAntwort