求和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.
更多推荐
发布评论