如何使用python中的for循环添加2D数组中的值

发布于 2025-02-05 07:38:52 字数 432 浏览 2 评论 0原文

if __name__ == '__main__':

scores = [[8, 1], [5, 3], [3, 5], [8, 1], [7, 1], [1, 0], [9, 0], [5, 0], [6, 0], [8, 1, 0]]
#scores_int = 0;
#scores_int = len(scores);
sum = 0;


for row in range(len(scores)):
    sum = scores[0]
print(sum)
print(scores[0:1])
print(scores[1][0])
   #print("Sum of all all the socres:", sum);

因此,我试图找出一种循环浏览数组的每个实例,并将值添加到总和变量中的方法,但是我不明白如何循环循环2D数组。得分总和应等于72 我只需要语法帮助for循环

if __name__ == '__main__':

scores = [[8, 1], [5, 3], [3, 5], [8, 1], [7, 1], [1, 0], [9, 0], [5, 0], [6, 0], [8, 1, 0]]
#scores_int = 0;
#scores_int = len(scores);
sum = 0;


for row in range(len(scores)):
    sum = scores[0]
print(sum)
print(scores[0:1])
print(scores[1][0])
   #print("Sum of all all the socres:", sum);

So im trying to figure out a way to loop through every instance of the array and add the values in them to a sum variable, but i dont understand how to loop through a 2d array. The score sum should equal 72
i just need syntax help with the for loop

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

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

发布评论

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

评论(1

執念 2025-02-12 07:38:52

我的建议,如果您只是为了尝试您不知道的事情。
下次您可以打印所有数字列表,然后尝试将其概括,avg或计算其中的数字

if __name__ == '__main__':
    scores = [[8, 1], [5, 3], [3, 5], [8, 1], [7, 1], [1, 0], [9, 0], [5, 0], [6, 0], [8, 1, 0]]
    total = 0
    
    for list_of_number in scores:
        # print(list_of_number)
        total += sum(list_of_number)
    
    print(total)

My advice if you're begginer is just to experiment with things you don't know.
Next time you could print all the list of numbers and then try to sum it , avg it, or count the numbers inside it

if __name__ == '__main__':
    scores = [[8, 1], [5, 3], [3, 5], [8, 1], [7, 1], [1, 0], [9, 0], [5, 0], [6, 0], [8, 1, 0]]
    total = 0
    
    for list_of_number in scores:
        # print(list_of_number)
        total += sum(list_of_number)
    
    print(total)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文