简体   繁体   中英

Use lambda instead of itemgetter in python

Using sort is it possible to use a list [2, 5] or [2, 5, 6] or only [2], as an argument with itemgetter:

list_items = [2, 5, 6]
sorted(table_rows, key=itemgetter(*list_items), reverse=rev)

But I don't know how to have the same behavior with lambda function, only works with one element, with more it give me an error "TypeError: tuple indices must be integers, not list"

sorted(table_rows, key=lambda x:x(list_items), reverse=rev)

You could always directly construct the tuple:

sorted(table_rows, key=lambda x:tuple(x[i] for i in list_items), reverse=rev)

This is effectively what itemgetter() does.

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