Python using combinations to sum values in a tuple in a list in a dictionary? -
i trying sum combination of values list of tuples in dictionary. example, dictionary contains:
dict = {1: [(2, 2), (4, 3), (6, 1), (7, 1), (8, 3)], 2: [(4, 1), (5, 3), (1, 2)],...}
and goes on multiple entries. i'm trying sum second value of tuples each entry in many combinations sum maximum of 4. entry 1, desired output be:
{1: [(2, 6, 3), (2, 7, 3), (4, 6, 4), (4, 7, 4), (6, 7, 2), (8, 6, 4), (8, 7, 4)]
where third value in tuple sum of combinations of second value of previous tuples, , first , second values of tuple associated first values of previous tuples.
i have tried following code:
for key, value in dict.items(): object1 = key mylist = value tup in mylist: object2 = tup[0] pair = tup[1] combo = itertools.combinations(tup[1],2) sum = {k:sum(j _,j in v) k,v in combo} if sum <= 4: print(sum)
and error
'numpy.float64' object not iterable
i think error stems "combo" , possibly use of itertools. unsure if need fix section of code or if way off base in approach.
yes, can itertools.combinations
, have pass right arguments. :) need pass list of tuples can make pairs of tuples. could comprehensions, think using traditional for
loops makes easier read.
as others have mentioned, there other problems code, apart not passing right things combinations
. main 1 being you're assigning dictionary name sum
, shadows sum
built-in function you're trying use. , attempt compare dictionary integer 4, doesn't make lot of sense. :)
anyway, here's code want. note in expected output messed last 2 tuples: (8, 6, 4)
, (8, 7, 4)
should (6, 8, 4)
, (7, 8, 4)
, respectively.
from itertools import combinations = { 1: [(2, 2), (4, 3), (6, 1), (7, 1), (8, 3)], 2: [(4, 1), (5, 3), (1, 2)], } new_dict = {} k, seq in a.items(): c = [] (u,v), (x,y) in combinations(seq, 2): total = v + y if total <= 4: c.append((u, x, total)) new_dict[k] = c k, seq in new_dict.items(): print(k, seq)
output
1 [(2, 6, 3), (2, 7, 3), (4, 6, 4), (4, 7, 4), (6, 7, 2), (6, 8, 4), (7, 8, 4)] 2 [(4, 5, 4), (4, 1, 3)]
combinations(seq, 2)
yields pairs of tuples, , can unpack tuples individual numbers with
for (u,v), (x,y) in combinations(seq, 2):
we could have done like
for t0, t1 in combinations(seq, 2):
and unpacked t0
, t1
tuples in separate step, or used indexing items. eg,
for t0, t1 in combinations(seq, 2): total = t0[1] + t1[1] if total <= 4: c.append((t[0], t[1], total))
but think previous way less cluttered.
but if insist on doing comprehensions, can:
new_dict = {k: [(u, x, v+y) (u,v), (x,y) in combinations(seq, 2) if v+y <= 4] k, seq in a.items()}
note less efficient previous versions because computes v+y
twice every combination passes v+y <= 4
test.
Comments
Post a Comment