a=[[1,2,3],[4,5,6],[7,8,9]]
.pop() has the capacity to not only remove an element of a list but also return that element.
I am looking for a similar function that can remove and return a whole list that could exist in the middle of another list.
E.g is there a function that will remove [4,5,6] from the above list a, and return it.
The reason for the question is that I'm sorting a list through itemgetter and there's a collision between the headings row (string) and the rest of the data (datetime). As such, I'm looking to effectively pop the list which represents the headings, do a sort, then insert it back in.
解决方案
The nested lists are just values in the outer list. Just use .pop() on that outer list:
inner_list = a.pop(1)
Demo:
>>> a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> a.pop(1)
[4, 5, 6]
>>> a
[[1, 2, 3], [7, 8, 9]]
You could just use a slice to remove the first row from consideration if a header row is in the way:
result = rows[:1] + sorted(rows[1:], key=itemgetter(1))