Reputation: 1387
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']]
I have another list as:
guest_list = [0.5, 0.0, 1.0]
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.
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 will be:
new_list = [ 0.1111, 0, .4444]
This was done by [ 2/9 * guest_list[0] , 3/9 * guest_list[1], 4/9 * guest_list[2] ]
I just know I can count 1D lists using list.count but I'm finding it difficult to implement the above logic in Python.
Upvotes: 2
Views: 5008
Reputation: 114579
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, row in 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).
Upvotes: 4
Reputation: 60197
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 * factor for n, factor in zip(numbers, guest_list)]
#>>> [0.1111111111111111, 0.0, 0.4444444444444444]
If using Python 2, use v.isdigit()
and convert total_numbers
to a float.
Upvotes: 1