简体   繁体   English

如何从嵌套列表中的每个子列表中提取直到倒数第二个元素?

[英]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:所需的 output 是:

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: output:

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

You can try this:你可以试试这个:

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

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

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