我想从现有列表中创建一个新列表,这样新列表中的每个元素都是现有列表中所有数字的乘积,除了新列表元素中相同位置的元素。
例如 [2,4,5] --> [20,10,8]
我想出了一个解决方案,其中一个 for 循环,j 遍历到第 i 个(当前)元素的右侧,而在另一个 for 循环中,k 覆盖元素的左侧 - 相乘并给出结果.
def mulList():
oldList = [2,4,5]
newList = []
for i in range(len(oldList)):
a = 1
for j in range(i+1,len(oldList)):
a *= oldList[j]
for j in range(i-1,-1,-1):
a *= oldList[j]
newList.append(a)
print(newList)
mulList()
后来我知道我们可以用两个这样的for循环来解决它,如果我等于j,我什么都不做
def mulList():
oldList = [2,4,5]
newList = []
for i in range(len(oldList)):
a = 1
for j in range(len(oldList)):
if j == i:
a += 0
else:
a *= oldList[j]
newList.append(a)
print(newList)
mulList()
我想知道是否有更好的方法可以只用一个for循环来解决。
请您参考如下方法:
您可以只将所有内容相乘一次,然后再次遍历元素并将总积除以当前元素:
def mulList():
oldList = [2,4,5]
newList = []
total = 1
for x in oldList:
total *= x # total = total * x
for x in oldList:
# Use // to get int (4) instead of float (4.0)
newList.append(total // x)
print(newList)
