Skip to content Skip to sidebar Skip to footer

Count Number Of Elements In Each Row In 2d List

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',

Solution 1:

To get the total number of numbers (assuming only the first element in each row is a letter you want to skip) you can just use

total_numbers = sum(map(len, partition2d)) - len(partition2d)

i.e. summing the length of all rows and subtracting the number of rows.

Then you can get the result you're looking for with

result= [guest * (len(row) -1.0) / total_numbers
          for guest, rowin zip(guest_list, partition2d)]

zip is used to get pairs with one element (guest) from guest_list and one row from partition2d. Then the result is computed.

Note that the 1.0 is there (instead of a simple 1) to ensure that division is done in floating point because having guest_list containing integers would give surprising results in Python 2.x (this has been fixed in Python 3.x, but in Python 2.x 3/4 by default gives 0 as result).

Solution 2:

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

guest_list = [0.5, 0.0, 1.0]

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]

otherwise

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

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

is more thorough

total_numbers = sum(numbers)

total_numbers
#>>> 9

And then you can multiply it through

[n/total_numbers * factorfor n, factorin zip(numbers, guest_list)]
#>>> [0.1111111111111111, 0.0, 0.4444444444444444]

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

Post a Comment for "Count Number Of Elements In Each Row In 2d List"