简体   繁体   中英

Lambda sorting issue in Python3

My python2.7 code contains lambda sort technique to sort fetched elements according to the defined order. Yesterday i migrated from python 2.7 to python 3.6, The problem is after migration the line where i wrote lambda sort is throwing error in program. For migration from py2 to py3 i used lib2to3. I believe this is cause of some syntax miss match in py3, But couldn't figure it out. The error log is as mentioned below-

My code Fragment:


 property_sort_order = ['field', 'rename', 'selected', 'description']
        node_property_value_list = []
        node_property_value_list = node_property_value[nodekey]
        node_property_value_list = [OrderedDict(
             sorted(item.iteritems(), key=lambda (k, v): property_sort_order.index(k)))
                                for item in node_property_value_list]
                                    for item in node_property_value_list]
        #print node_property_value_list
        node_property_value[nodekey] = node_property_value_list

Errror:
        for item in node_property_value_list]
    TypeError: <lambda>() missing 1 required positional argument: 'v'

In Python 2 it is possible to unpack the (k, v) tuple in lambda/function arguments, but not in Python 3 . You can either unpack the lambda inline,

lambda item: property_sort_order.index(item[0])

or unpack as a separate statement (which can't be done in a lambda).

def sort_key(item):
    k, v = item
    return property_sort_order.index(k)
sorted(..., key=sort_key)

您需要使key=lambda k, v: property_sort_order.index(k)成为key=lambda k_v:property_sort_order.index(k_v[0]) -lambda通过单个元组,您无法在python3中对其进行破坏.6。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM