【问题标题】:How to find which elements in one array sum up to each element in the other? [duplicate]如何找到一个数组中的哪些元素与另一个数组中的每个元素相加? [复制]
【发布时间】:2020-03-30 01:43:42
【问题描述】:

假设:

reversedPriv = [52,27,13,6,3,2]
array= [9] #For this example we only used one element in the array, assume more elements
var = 0
numA = []
for i in array:
    for j in reversedPriv:
        while var!= j:
            if j < i:
                var = var + j
                numA.append(j)
                numA.sort()
print(numA)

我希望它可以append [3,6]numA 并打印,但它目前什么也没做。我忽略的 while 循环是否存在某些条件?

代码的重点是找出reversedPriv 中的哪些元素与array 中的每个元素相加,并将它们附加到列表numA 中。例如,reversedPriv 列表中只有 6 和 3 的总和为 9。所以numA = [3,6] 目前“数组”只有一个元素,但代码应该能够将其放大 n 个元素。

【问题讨论】:

标签: python arrays list debugging encryption


【解决方案1】:

这是一种熊猫方法:

import itertools 
import pandas as pd
df = pd.DataFrame(itertools.combinations( [52,27,13,6,3,2], 2))  
nums = [9] 
df['sum'] = df[0] + df[1] 
matches=[] 
for num in nums: 
    matches.append(list(df.loc[df['sum'] == num][0]) + list(df.loc[df['sum'] == num][1])) 

matches
# [[6, 3]]  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多