在嵌套列表中添加元素

发布于 2025-01-17 10:29:14 字数 224 浏览 4 评论 0原文

我有这个问题,我想计算列表和子列表中有多少个整数。

我有这段代码,但似乎不起作用:

x = [[1, 3], [0], [2, -4]]

count = 0pos = 0

for i in x[pos]:count = count + len(x[pos])pos = pos + 1

    print(count)

预期 5,因为有 5 个元素。

I have this problem, I want to count how many integers in a list AND sub-lists.

I have this code but doesn't seem to be working:

x = [[1, 3], [0], [2, -4]]

count = 0pos = 0

for i in x[pos]:count = count + len(x[pos])pos = pos + 1

    print(count)

Expected 5 because there are 5 elements.

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

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

发布评论

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

评论(1

沉溺在你眼里的海 2025-01-24 10:29:14

我已将您的代码编辑为以下内容:

x = [[1, 3], [0], [2, -4]]

count = 0

for arr in x:
    for element in arr:
        count +=1
print(count)

I've edited your code to the following:

x = [[1, 3], [0], [2, -4]]

count = 0

for arr in x:
    for element in arr:
        count +=1
print(count)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文