Reputation: 351
#create a simple list in python
#list comprehension
x = [i for i in range(100)]
print (x)
#using loops
squares = []
for x in range(10):
squares.append(x**2)
print (squares)
multiples = k*[z for z in x] for k in squares
So in the last line of code I am trying to multiply both the lists. the problem is the lists are not of the same side and k*[z for z in x] this part is also incorrect.
Upvotes: 2
Views: 1310
Reputation: 7058
For problems with iteration, I suggest anyone to check Loop Like A Native by Ned Batchelder and Looping like a Pro by David Baumgold
If you want to multiply them as far as the shortest list goes, zip
is your friend:
multiples = [a * b for a, b in zip (x, squares)]
If you want a matrix with the product, then you can do it like this
result = [
[a * b for a in x]
for b in squares
]
Upvotes: 1
Reputation: 2894
I don't quite understand what the desired output would be. As the function stands now, you would have a list of lists, where the first element has 100 elements, the second one 400, the third 900, and so on.
[z for z in x]
defines a list that is identical to x. So, you might just write k*x
[[k*z for z in x] for k in squares]
. This would lead to a list of 10 lists of 100 elements (or a 10x100-matrix) containing the products of your lists.Upvotes: 1
Reputation: 88
You can loop on each array to multiply element by element at the same position in a result array:
i = 0
arrayRes = []
while i < min (len(array1),len(array2)):
arrayRes.append(array1[i]*array2[i])
i+=1
Or do you prefer to multiply them, matrix way?
x = 0
y = 0
arrayRes = []
while x < len(array1):
arrayRes.append([])
while y < len(array2):
arrayRes[x].append(array1[x]*array2[y])
y+=1
x+=1
Upvotes: -1