The output I was getting was just integers (ie. 2,6,9). Desired output was a list (ie. [2,6,9] ).
def multiplyNums(aList):
for (i,j) in enumerate(aList):
newList = []
if i < (len(aList)-1):
newList = (aList[i] * aList[i+1])
x = print(newList,end=',')
else:
newList = (aList[i] * aList[i])
x = print(newList)
return x
Is it that you would like to produce a list which contains the value of each entry multiplied by the following value (and the last value squared)?
ie. [2,3,4] -> [2*3, 3*4, 4*4] ?
If so then I think you should probably do:
def multiplyNums(aList):
newList = []
for (i,j) in enumerate(aList):
if i < (len(aList)-1):
newList.append(aList[i] * aList[i+1])
else:
newList.append(aList[i] * aList[i])
return newList
print multiplyNums( [2, 3, 4] )
Here is a funny single line list comprehension:
def multiplyNums(a):
return [x[0]*x[1] for x in zip(a,a[1:]+[a[-1]])]
A cleaner way to do this would be :
def multiplySuccessor(aList):
newList = []
for i in range(len(aList)-1):
newList.append(aList[i] * aList[i+1])
newList.append(aList[len(aList)-1]**2)
return newList
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.