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 开发者_如何学Goanother list.
I'm supposed to return 4 with "one expression and no parenthesis"[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.
>>> 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. 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 = [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, 2, [1, 1, 1, 3, 4]]
>>> a[-1][-1]
[1, 1, 1, 3, 4]
>>> a[-1][-1][-1]
4
精彩评论