求和2D列表列,其中一些元素是字符串(Summing 2D list columns where some elements are strings)

编程入门 行业动态 更新时间:2024-10-24 12:26:31
求和2D列表列,其中一些元素是字符串(Summing 2D list columns where some elements are strings)

我有一个表格列表清单:

my_list=[[1,2,'A'],[4,5,'B'],[7,8,'C']]

我想总结每个列表的第一个元素(1 + 4 + 7)来得到一个总数。 我尝试了以下无法正常工作,因为列表中的某些元素是字符串:

new_list = list(zip(*my_list)) print (sum(new_list[0]))

不使用循环的最佳方法是什么?

I have a list of lists of the form:

my_list=[[1,2,'A'],[4,5,'B'],[7,8,'C']]

and I want to sum the first element of each list (1+4+7) to get a total. I tried the following which didn't work because some elements of the list are strings:

new_list = list(zip(*my_list)) print (sum(new_list[0]))

What is the best way to do this without using loops?

最满意答案

sum(a[0] for a in my_list)

足够了。

sum(a[0] for a in my_list)

is sufficient.

更多推荐

本文发布于:2023-08-05 21:27:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1438354.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   元素   列表   Summing   strings

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!