Python 函数将列表中的元素乘以它旁边的数字
我正在写一个函数,将列表中的元素与它旁边的数字相乘,最后一个数字本身相乘。这是密码Python 函数将列表中的元素乘以它旁边的数字,python,list,multiplication,Python,List,Multiplication,我正在写一个函数,将列表中的元素与它旁边的数字相乘,最后一个数字本身相乘。这是密码 def multiplyNums(aList): newList=[] for x in range(len(aList)): if x < len(aList): newList.append(aList[x]*aList[x+1]) else: newList.append(aList
def multiplyNums(aList):
newList=[]
for x in range(len(aList)):
if x < len(aList):
newList.append(aList[x]*aList[x+1])
else:
newList.append(aList[x]*aList[x])
return (newList)
我真的认为这会奏效,但范围有问题吗?在第5行 你走得太远了。请注意,列表中的最后一个元素具有索引lenaList-1 更改此项:
if x < len(aList):
与:
另一种使用itertools的方法是,用自己压缩列表,但要压缩第一个元素,用mul运算符映射结果,将其转换为列表,并将最后一个元素的乘法与自己连接起来:
import operator
import itertools
def multiplyNums(aList):
return list(itertools.starmap(operator.mul, itertools.izip(aList, aList[1:]))) + [aList[-1]*aList[-1]]
print(multiplyNums([1,2,3,4,5,6]))
[2, 6, 12, 20, 30, 36]
你能详细说明一些错误吗?提供a.只需将条件设置为如果x
import operator
import itertools
def multiplyNums(aList):
return list(itertools.starmap(operator.mul, itertools.izip(aList, aList[1:]))) + [aList[-1]*aList[-1]]
print(multiplyNums([1,2,3,4,5,6]))
[2, 6, 12, 20, 30, 36]