简体   繁体   中英

How do you extract till the second last element from each sub-list in a nested list?

How do you extract till the second last element from each sub-list in a nested list?

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

The desired output is:

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

You can use the following method to do this:

x = [[1, 2, 3], [4, 5], [7, 8, 9], [1, 3, 5, 6, 8]]
y = [sublist[:-1] for sublist in x]

output:

[[1, 2], [4], [7, 8], [1, 3, 5, 6]]

You can try this:

y = [ar[:-1] for ar in x]

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