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

发布于 2024-12-07 04:01:18 字数 181 浏览 3 评论 0原文

我正在用 Python 进行基础编程课程的实验,但我不知道如何在另一个列表中返回一个列表中的数字。
我应该用“一个表达式,没有括号”返回 4

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

有什么想法吗? 到目前为止我所得到的只是返回 [2,[3,4]] 并且我无法弄清楚除此之外的任何内容。

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

优雅的叶子 2024-12-14 04:01:18
>>> a = [1,[2,[3,4]]]
>>> a[1]
[2, [3, 4]]
>>> a[1][1]
[3, 4]
>>> a[1][1][1]
4
>>> 
>>> a = [1,[2,[3,4]]]
>>> a[1]
[2, [3, 4]]
>>> a[1][1]
[3, 4]
>>> a[1][1][1]
4
>>> 
鹤仙姿 2024-12-14 04:01:18

一种表达:

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

One expression:

>>> [1,[2,[3,4]]][1][1][1]
4
铁憨憨 2024-12-14 04:01:18

如果您不知道,要访问列表的最后一个元素,可以使用负索引。 a[-1] 表示倒数第一个元素。当您想要打印相对于末尾的位置的元素时,它非常有用。

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

假设您有一个不同的 a。
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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文