【问题标题】:How to multiply responding indexes of two lists如何将两个列表的响应索引相乘
【发布时间】:2021-11-13 17:12:37
【问题描述】:

我有两个列表:

firstList = [1,2]
secondList = [3,4]

我的目标是乘以匹配索引并将它们相加,假设列表始终具有相同但不是硬编码的长度。

结果:

1 * 3 + 2 * 4 = 11

我想要不使用现有函数的解决方案。

【问题讨论】:

  • 你试过了吗?它是否部分工作?
  • 你有什么尝试? zip 对您来说听起来如何。请解释一下现有功能是什么意思?

标签: python list algorithm


【解决方案1】:

如果您不想使用任何预建函数,可以这样做:


def dot(firstList, secondList):
    summation = 0
    idx = 0
    for i in firstList:
        summation += i * secondList[idx]
        idx += 1
    return summation
        

如果你对 range 和 len 没问题:

def dot(l1, l2):
    temp = [l1[i]*l2[i] for i in range(len(l1))]
    summation = 0
    for i in temp:
        summation += i
    return summation

如果你对 sum 函数没问题:

def dot(l1, l2):
    return  sum(l1[i]*l2[i] for i in range(len(l1)))

您也可以为了安全添加:

assert len(l1) == len(l2)

【讨论】:

  • 想知道sumrange len 是否不被视为现有功能?~。 :-)。这个OP对我来说很模棱两可...
  • 我觉得它们不是,因为许多 for 循环都需要它们,但如果他需要手动完成,我会调整:)
  • 添加了仅使用 for 循环的解决方案 :)
  • 请注意,使用sum 时不需要使用括号[ ]。事实上,使用它们通常更有效率。最后一种选择:sum(x*y for x,y in zip(l1,l2))
  • 好收获,已更新
【解决方案2】:

这是一个使用简单迭代和索引值的可能解决方案。
我们清楚地假设列表总是相同的长度:

firstList = [1,2]
secondList = [3,4]

result = 0
index = 0
for item in firstList:
    result += firstList[index] * secondList[index]
    index += 1


print(result)

输出
11

【讨论】:

    【解决方案3】:

    一个简单的解决方案是遍历firstList 并进行计算。最后,总结结果。为此,您可以使用sum 函数,或轻松使用简单的循环。

    # you can use `simpleLen` instead of `len`
    multiplications = [i * secondList[i-1] for i in firstList if i <= len(secondList)]
    # loop to sum elements of multiplications or only `sum(multiplications)`
    result = 0
    for j in multiplications:
        result += j
    
    print(result)
    

    但是,如果您对len 功能不满意,可以通过以下方式轻松实现:

    def simpleLen(input_list):
        count = 0
        for i in input_list:
            count += 1
        return count
    

    其次,如果你只想要两个列表的乘积,你可以这样做:

    # if suppose the length of arrays are the same
    idx = 0
    result = 0
    lenght_of_arr = simpleLen(firstList)
    while idx < lenght_of_arr:
        result += (firstList[idx] * secondList[idx])
        idx += 1
    

    【讨论】:

    • 问题 - 如果 firstList 有 [5, 6] 怎么办。这行不通!
    • @DanielHao 更新了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-20
    • 1970-01-01
    • 2018-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多