快速对每个数组元素对执行操作

时间:2015-10-16 17:18:16

标签: python arrays

我有一个数组A

A = [5,2,8,14,6,13]

我想得到一个数组,其中每个元素被添加到每个其他元素,所以前五个元素将是5 +每个元素,然后接下来的四个元素将是2 +每个元素等。 所以结果将是

B = [7,13,19,11,18,   10,16,8,15,   22,14,21,   20,27,   19]

如果不使用for循环,最快的方法是什么?

注意:我试图解决的问题涉及大布尔数组而不是整数,实际操作是布尔'和',而不仅仅是加法。为了便于解释,我简化了问题。到目前为止,我一直在使用for循环,但我正在寻找更快的替代方案。

3 个答案:

答案 0 :(得分:5)

使用“itertools.combinations

from itertools import combinations
a = [5,2,8,14,6,13]

print [sum(i) for i in list(combinations(a, 2))]

不需要list()。感谢@PeterWood

print [sum(i) for i in combinations(a, 2)]

输出:

  

[7,13,19,11,18,10,16,8,15,22,14,21,20,27,19]

Demo

答案 1 :(得分:1)

你可以递归地做到:

def add_value_to_rest(sequence):
    if not sequence:
        return []
    else:
        additional = sequence[0]
        return ([additional + value for value in sequence] +
                add_value_to_rest(sequence[1:]))

使用生成器,在Python 3中:

def add_value_to_rest(sequence):
    if sequence:
        additional = sequence[0]
        for value in sequence:
            yield additional + value
        yield from add_value_to_rest(sequence[1:])

或者使用Python 2.7:

def add_value_to_rest(sequence):
    if sequence:
        additional = sequence[0]
        for value in sequence:
            yield additional + value
        for value in add_value_to_rest(sequence[1:]):
            yield value

答案 2 :(得分:-2)

A = [5,2,8,14,6,13]
B = []
for i, x in enumerate(A):
    for l in range(len(A) - i - 1):
        B.append(A[i] + A[i + l + 1])
print B
#[7, 13, 19, 11, 18, 10, 16, 8, 15, 22, 14, 21, 20, 27, 19]