简体   繁体   中英

Finding all combinations in vector

I have one question about python: Let's say I have a vector which has the form

a = [ [[0.58, 0.0001], [0.43, 0.002]], 
[[0.55, 0.1], [0.45, 0.2]], 
[[0.7, 0.0021], [0.3, 0.2]] ]

The 0.58 and 0.43 is a probability as well as 0.55 and 0.45, and 0.7 and 0.3. I would like to get p1=0.58 * 0.55 * 0.7, p2=0.58 * 0.45 * 0.7, etc., so all possibilities in a tree diagram. The best output would also consider the corresponding value, so something like

[p1, (0.0001, 0.1, 0.0021)], [p2, (0.0001, 0.2, 0.0021)], ...

Thank you very much!

A bit of a util overload, but this will work.

  1. Generate the cartesian (cross) product over all top-level sublists
  2. For each of the resulting triplets of pairs
    a. reduce their first elements by multiplication
    b.pack their second elements into a tuple

Code:

from itertools import product
from functools import reduce
from operator import mul, itemgetter as ig

[(reduce(mul, map(ig(0), p)), tuple(map(ig(1), p))) for p in  product(*a)]
# [(0.2233, (0.0001, 0.1, 0.0021)), 
#  (0.0957, (0.0001, 0.1, 0.2)), 
#  (0.1827, (0.0001, 0.2, 0.0021)),
#  (0.0783, (0.0001, 0.2, 0.2)), 
#  (0.16555, (0.002, 0.1, 0.0021)), 
#  (0.07095, (0.002, 0.1, 0.2)), 
#  (0.13545, (0.002, 0.2, 0.0021)), 
#  (0.05805, (0.002, 0.2, 0.2))]

Some documentation:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM