ato*_*3ls 5 python arrays grouping numpy set
假设我有一组值:
a = np.array([1,5,4,2,4,3,1,2,4])
Run Code Online (Sandbox Code Playgroud)
和三个'和'值:
b = 10
c = 9
d = 7
Run Code Online (Sandbox Code Playgroud)
有没有办法a将值组合成组的组,其中值组合起来等于b,c和d?例如:
b: [5,2,3]
c: [4,4,1]
d: [4,2,1]
b: [5,4,1]
c: [2,4,3]
d: [4,2,1]
b: [4,2,4]
c: [5,4]
d: [1,1,2,3]
Run Code Online (Sandbox Code Playgroud)
注意总和b,c并且d应该保持不变(== 26).也许这个操作已经有了名字?
这是使用 itertools 的简单实现
from itertools import chain, combinations
def group(n, iterable):
s = list(iterable)
return [c for c in chain.from_iterable(combinations(s, r)
for r in range(len(s)+1))
if sum(c) == n]
Run Code Online (Sandbox Code Playgroud)
group(5, range(5))
Run Code Online (Sandbox Code Playgroud)
产量
[(1, 4), (2, 3), (0, 1, 4), (0, 2, 3)]
Run Code Online (Sandbox Code Playgroud)
请注意,对于大型列表来说,这可能会非常慢,因为我们本质上是通过该列表的幂集来构建和过滤。
你可以用这个
sum_vals = [10, 9, 7]
a = [1, 5, 4, 2, 4, 3, 1, 2, 4]
map(lambda x: group(x, a), sum_vals)
Run Code Online (Sandbox Code Playgroud)
然后zip他们在一起。