簡體   English   中英

如何從嵌套列表中的每個子列表中提取直到倒數第二個元素?

[英]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]]

所需的 output 是:

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

您可以使用以下方法來執行此操作:

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

你可以試試這個:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM