简体   繁体   中英

How to divide all items in one list using all items in another list, and doing all possible combinations?

I'm having a bit of a problem here. For example, there are 2 lists:

a=[12,3,4,6,2]
b=[6,2,1,3,12]

What I want to do is make a new list which consists of:

c=[2,6,12,4,1,0.5, ...]

Also, is there any way to do this without importing anything?

Using set comprehension (to prevent duplicated items):

>>> a = [12,3,4,6,2]
>>> b = [6,2,1,3,12]
>>> c = {x/y for x in a for y in b}  # float(x)/y  in Python 2.x
>>> c
{0.5, 1.0, 2.0, 1.5, 4.0, 3.0, 6.0, 0.25, 0.6666666666666666, 1.3333333333333333, 
 0.16666666666666666, 12.0, 0.3333333333333333}

Use list to get a list object instead of a set :

>>> list(c)
[0.5, 1.0, 2.0, 1.5, 4.0, 3.0, 6.0, 0.25, 0.6666666666666666, 1.3333333333333333,
 0.16666666666666666, 12.0, 0.3333333333333333]

You could use list comprehensions:

 [float(x)/y for x in a for y in b] [2.0, 6.0, 12.0, 4.0, 1.0, 0.5, 1.5, 3.0, 1.0, 0.25, 0.6666666666666666, 2.0, 4.0, 1.3333333333333333, 0.3333333333333333, 1.0, 3.0, 6.0, 2.0, 0.5, 0.3333333333333333, 1.0, 2.0, 0.6666666666666666, 0.16666666666666666] 

If you want the result in fractions you should import the fractions module:

 import fractions set([fractions.Fraction(x)/y for x in a for y in b]) set([Fraction(1, 2), Fraction(1, 1), Fraction(2, 1), Fraction(3, 1), Fraction(4, 1), Fraction(6, 1), Fraction(12, 1), Fraction(1, 3), Fraction(2, 3), Fraction(4, 3), Fraction(1, 6), Fraction(1, 4), Fraction(3, 2)]) 

You can use itertools.product to get all the pairs to substract:

>>> import itertools
>>> pairs = list(itertools.product(*(a,b)))
>>> pairs
[(12, 6), (12, 2), (12, 1), (12, 3), (12, 12), (3, 6), (3, 2), (3, 1), (3, 3), (3, 12), (4, 6), (4, 2), (4, 1), (4, 3), (4, 12), (6, 6), (6, 2), (6, 1), (6, 3), (6, 12), (2, 6), (2, 2), (2, 1), (2, 3), (2, 12)]

Then you divide:

>>> [a/b for a,b in pairs]
[2, 6, 12, 4, 1, 0, 1, 3, 1, 0, 0, 2, 4, 1, 0, 1, 3, 6, 2, 0, 0, 1, 2, 0, 0]
>>> 

If you want floats:

>>> [float(a)/b for a,b in pairs]
[2.0, 6.0, 12.0, 4.0, 1.0, 0.5, 1.5, 3.0, 1.0, 0.25, 0.6666666666666666, 2.0, 4.0, 1.3333333333333333, 0.3333333333333333, 1.0, 3.0, 6.0, 2.0, 0.5, 0.3333333333333333, 1.0, 2.0, 0.6666666666666666, 0.16666666666666666]

Putting all together in a one-liner:

>>> [float(a)/b for a,b in it.product(*(a,b))]

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