[英]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: 例如,有2个列表:
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
获取列表对象而不是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: 您可以使用itertools.product
减去所有对。
>>> 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))]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.