简体   繁体   English

Python-切片列表以获取列表中的第一项(切片列表)

[英]Python - Slicing lists to get the first item in the list (Slicing lists of lists)

How do I slice a list to get rid of "Hello","World" and "Monty" in each list of lists? 如何分割列表以摆脱每个列表中的“ Hello”,“ World”和“ Monty”?

I may have worded that incorrectly, but this is what I mean: 我的措词可能不正确,但这就是我的意思:

 lst1 = [["Hello", 1,2,3], ["World",4,5,6],["Monty",7,8,9]]

And I want to get this: 我想得到这个:

lst2 = [[1,2,3],[4,5,6],[7,8,9]]

Thank you for your help. 谢谢您的帮助。

You can reach it with a list comprehension and get in each iteration the last elements beside the first of the nested list by using the [1:] selector. 您可以通过列表理解来达到此目的,并在每次迭代中使用[1:]选择器获得嵌套列表中第一个嵌套元素之外的最后一个元素。

lst1 = [["Hello", 1,2,3], ["World",4,5,6],["Monty",7,8,9]]

lst2 = [item[1:] for item in lst1]
print (lst2)
# [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

You can get a slice of a list lst starting with the second element using lst[1:] . 您可以使用lst[1:]从第二个元素开始获取列表lst To do it for each sublist you can use a list comprehension : 为此,您可以使用列表推导

>>> lst1 = [["Hello", 1, 2, 3], ["World", 4, 5, 6], ["Monty", 7, 8, 9]]
>>> lst2 = [lst[1:] for lst in lst1]
>>> lst2
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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