简体   繁体   English

返回嵌套列表中的项目(python)

[英]Return an item in a nested list (python)

I'm doing a lab for a basic programming class in Python, and I can't figure out how to return a number in a list, in another list. 我正在为使用Python的基本编程类做实验,但我不知道如何在一个列表和另一个列表中返回数字。
I'm supposed to return 4 with "one expression and no parenthesis" 我应该以“一个表达式且没有括号”返回4

[1,[2,[3,4]]]

Any ideas? 有任何想法吗? All I've gotten so far is returning [2,[3,4]] and I haven't been able to figure out anything past that. 到目前为止,我所得到的只是返回[2,[3,4]],而我还无法找出任何超出的内容。

>>> a = [1,[2,[3,4]]]
>>> a[1]
[2, [3, 4]]
>>> a[1][1]
[3, 4]
>>> a[1][1][1]
4
>>> 

One expression: 一种表达方式:

>>> [1,[2,[3,4]]][1][1][1]
4

In case you don't know, to access the last element of a list you can use negative index. 如果您不知道,可以使用负索引来访问列表的最后一个元素。 a[-1] means the first element from the end. a [-1]表示从末尾开始的第一个元素。 It's very useful when you want to print elements with position relative to the end. 当您要打印相对于末端位置的元素时,这非常有用。

>>> a = [1,[2,[3,4]]]
>>> a[-1]
[2, [3, 4]]
>>> a[-1][-1]
[3, 4]
>>> a[-1][-1][-1]
4

Let's say you had a different a. 假设您有一个不同的a。
a = [1, 1, 1, 1, 1, 1,[1, 1, 1, 1, 2,[1, 1, 1, 3,4]]] The code above will still give you the last element. a = [1,1,1,1,1,1,[1,1,1,1,2,[1,1,1,3,4]]]上面的代码仍将为您提供最后一个元素。

>>> a = [1, 1, 1, 1, 1, 1,[1, 1, 1, 1, 2,[1, 1, 1, 3,4]]]
>>> a[-1]
[1, 1, 1, 1, 2, [1, 1, 1, 3, 4]]
>>> a[-1][-1]
[1, 1, 1, 3, 4]
>>> a[-1][-1][-1]
4

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

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