我有一个类似以下结构的嵌套列表:
nested_list = [ ['text1', index1], ['text2', index2], ['text3', index3], [], ..., ['text12', index54] ].
项“索引”是一个整数,不对应于列表的索引。您可以看到我也有一些空列表。
我想根据项“索引”对嵌套列表进行排序。我当前的方法失败了:
sorted_list = sorted(nested_list, key = lambda x: x[1])
我认为这是由于这些空列表所致,因为我收到以下错误消息:
IndexError
list index out of range
所以我尝试了以下操作:
sorted_list = sorted(nested_list, key = lambda x: x[1] if len(x) > 0)
sorted_list = sorted(nested_list, key = lambda x: x[1] and len(x) > 0)
但是所有这些都是语法错误。
我在做什么错了?
答案 0 :(得分:0)
conditional expression始终需要else
部分。如果条件不成立,该如何确定表达式的值呢?
sorted_list = sorted(nested_list, key = lambda x: x[1] if x else 0)
0
是否有用,取决于您的数据。如果您同时拥有index
的负值和正值,则空列表将排在中间。
答案 1 :(得分:0)
首先过滤掉“无”,然后对其进行排序。然后,您可以手动在末尾添加这些空列表。
sorted(filter(None, nested_list), key = lambda x: x[1])