简体   繁体   中英

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?

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.

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:] . 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]]

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