简体   繁体   English

嵌套列表使用索引和切片

[英]Nested List using indexing and slicing

How do I slice or index this list in order to get the answer below? 如何对此列表进行切片或索引以获得以下答案? I've tried doing multiple methods of slicing and nothing has worked for me. 我尝试过多种切片方法,没有任何方法可以帮助我。

L = [0, [], [1,2,3,4], [[5],[6,7]], [8,9,10]]
newL = [L[0],L[2][1],L[2][2],L[3][0]] 

Answer: [0, 2, 3, [5 ,6], 8, 10] 答案:[0,2,3,[5,6],8,10]

newL is what I have so far, but I can't seem to get the [6,7] split in the nested list. newL是我到目前为止所拥有的,但我似乎无法在嵌套列表中得到[6,7]。

We start with: 我们从:

L = [0, [], [1, 2, 3, 4], [[5], [6, 7]], [8, 9, 10]]

We want: 我们想要:

[0, 2, 3, [5, 6], 8, 10]

Let's start from the farthest inside. 让我们从最里面开始吧。 We need [5, 6] . 我们需要[5, 6] These are both buried : 这些都埋没了

>>> L[3][0][0]
5
>>> L[3][1][0]
6
>>> [L[3][0][0], L[3][1][0]]
[5, 6]

One layer farther out we need 2, 3 : 一层更远我们需要2, 3

>>> L[2][1]
2
>>> L[2][2]
3

Now put it together: 现在把它放在一起:

>>> [L[0], L[2][1], L[2][2], [L[3][0][0], L[3][1][0]], L[4][0], L[4][2]]
[0, 2, 3, [5, 6], 8, 10]

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

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