【问题标题】:python multiply all elements except ith element in list and return list [closed]python将列表中除第i个元素之外的所有元素相乘并返回列表[关闭]
【发布时间】:2021-09-21 06:01:27
【问题描述】:

假设我有一个 list 。我想将它的所有元素与第 i 个元素相乘。

例子:

  • 输入:[1,2,3,4]
  • 输出:[24,12,8,6]

这里是输出

 24 is 2*3*4
 12 is 1*3*4
 8 is 1*2*4
 6 is 1*2*3

任何帮助将不胜感激

【问题讨论】:

  • 你有没有尝试过?出了什么问题?
  • 奇怪的是接受一个在他之前 3 分钟告诉我的答案,最好使用enumerate

标签: python list multiplication


【解决方案1】:

使用itertools.combinations 的解决方案(并反转以获得正确的顺序)

from itertools import combinations
from operator import mul
from functools import reduce

values = [1, 2, 3, 4]
result = [reduce(mul, c) for c in combinations(reversed(values), r=len(values) - 1)]
print(result)  # [6, 8, 12, 24]

或者直接使用你的逻辑:迭代并且对于每个索引不要使用相应的值

values = [1, 2, 3, 4]
result = []
for i in range(len(values)):
    x = 1
    for idx, value in enumerate(values):
        if i != idx:
            x *= value
    result.append(x)

print(result)  # [24, 12, 8, 6]

【讨论】:

  • 你可以做combinations(reversed(values), r=len(values) - 1)
  • 还需要导入reduce from functools import reduce
【解决方案2】:

使用两个 for 循环的简单解决方案:

l=[1,2,3,4]
out=[]
for i in range(len(l)):
    prod=1 
    for j in range(len(l)):
        if(j!=i): #Iterate through list once more and compare the indices
            prod=prod*l[j]
    out.append(prod) 
print(out)

输出为:[24, 12, 8, 6]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-16
    • 1970-01-01
    • 1970-01-01
    • 2022-12-16
    • 1970-01-01
    • 1970-01-01
    • 2017-04-06
    • 2023-01-10
    相关资源
    最近更新 更多