计算2D列表中每一行的元素数量 [英] Count number of elements in each row in 2D list

查看:81
本文介绍了计算2D列表中每一行的元素数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个2D列表(可以随文件大小而变化),如下所示:

I have a 2D list (can be variable size depending on file) like this:

 partition2d =  [['A', '1', '5'],
                 ['B', '2', '3', '4'],
                 ['C', '6', '7', '8', '9']]

我还有另一个列表:

  guest_list = [0.5, 0.0, 1.0]

我要对partition2d的每一行中的整数(除具有'A','B'..这样的字符的第一列进行计数)以外的所有数字,然后将其除以partition2d中的整数总数.将会是

I want to count the number integers (except the first column which has chars like 'A','B'..) in each row of partition2d and divide this count by total number of integers in partition2d . Here it will be

count['1','5'] = 2. And count[ total integers in partition2d] = 9. 

我想将其分开.因此,我得到2/9并将此数字与guest_list的相应列相乘(即partition2d第一行的结果将与guest_list的第一列即0.5相乘,并将结果存储在新列表中.

I want to divide it. So I get 2/9 and multiply this number with the respective column of guest_list(that is result of first row of partition2d will be multiplied with first column i.e 0.5 of guest_list and store the result in a new list.

新列表将为:

  new_list = [ 0.1111, 0, .4444]   

这是由[2/9 * guest_list [0],3/9 * guest_list [1],4/9 * guest_list [2]]完成的

This was done by [ 2/9 * guest_list[0] , 3/9 * guest_list[1], 4/9 * guest_list[2] ]

我只是知道我可以使用list.count来计算一维列表,但是我发现很难在Python中实现上述逻辑.

I just know I can count 1D lists using list.count but I'm finding it difficult to implement the above logic in Python.

推荐答案

partition2d =  [['A', '1', '5'],
                ['B', '2', '3', '4'],
                ['C', '6', '7', '8', '9']]

guest_list = [0.5, 0.0, 1.0]

如果partition2d的列表始终为[字母,数字,数字,...]形式,则

If partition2d's lists are always of the form [letter, number, number, ...] then

numbers = [len(part)-1 for part in partition2d]

numbers
#>>> [2, 3, 4]

否则

numbers = [sum(v.isnumeric() for v in part) for part in partition2d]

numbers
#>>> [2, 3, 4]

更全面

total_numbers = sum(numbers)

total_numbers
#>>> 9

然后您可以将其乘以

[n/total_numbers * factor for n, factor in zip(numbers, guest_list)]
#>>> [0.1111111111111111, 0.0, 0.4444444444444444]


如果使用Python 2,请使用v.isdigit()并将total_numbers转换为浮点数.


If using Python 2, use v.isdigit() and convert total_numbers to a float.

这篇关于计算2D列表中每一行的元素数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆