'Brute force feature selection - sum items across list combinations
I have x lists of parameters & a list containing a list of the x lists. A total score is calculated by summing each corresponding item in each list.
For example, I have 2 lists & a main list like so:
a = [1,2]
b = [2,1]
mainList = ['a','b']
I want all the unique combinations - this is given by:
for L in range(0, len(mainList)+1):
for subset in itertools.combinations(mainList, L):
print(subset)
Output:
()
('a',)
('b',)
('a', 'b')
For each permutation, I wish to create a new list containing the overall score by summing the items of each included list.
So for example, in this case the desired outputs would be:
[0,0]
[1,2] #i.e. just a
[2,1] #i.e. just b
[3,3] #i.e. a+b
This is where I'm stuck - I'm not sure how to get the desired output above.
I suspect I'm overcomplicating it & there's just a quick way to do it.
Solution 1:[1]
What you need is to somehow connect a & b strings with corresponding lists. I think the cleanest way is to have a dictionary containing lists' names and lists with their values.
Here is an example:
list_dict = {'a': a, 'b': b}
for L in range(0, len(mainList)+1):
for subset in itertools.combinations(mainList, L):
temp = [0, 0]
for sub in subset:
temp[0] += list_dict[sub][0]
temp[1] += list_dict[sub][1]
print(temp)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | kcper |
