Python - 从列表列表中删除列表(类似于 .pop() 的功能)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21860605/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:45:52  来源:igfitidea点击:

Python - Remove list(s) from list of lists (Similar functionality to .pop() )

pythonpython-3.xlist

提问by Phoenix

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.

.pop() 不仅可以删除列表中的元素,还可以返回该元素。

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.

例如,是否有一个函数可以[4,5,6]从上面的列表中删除a并返回它。

The reason for the question is that I'm sorting a list through itemgetterand 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.

问题的原因是我正在对列表进行排序,itemgetter并且标题行(字符串)和其余数据(datetime)之间存在冲突。因此,我希望有效地弹出代表标题的列表,进行排序,然后将其重新插入。

采纳答案by Martijn Pieters

The nested lists are just values in the outer list. Just use .pop()on that outer list:

嵌套列表只是外部列表中的值。只需.pop()在该外部列表上使用:

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))