Reputation: 137
I'm doing an exercise where I create a function that receives two lists and returns the multiplications of the items at the same indices in a separate single list. Example:
transform("1 5 3", "2 6 -1")
#should return
[2, 30, -3]
To be clear, the program takes the items at index 1, 2 and 3 and multiplies them like this:
(1 * 2), (5 * 6), (3 * -1)
Now, the problem I face is that it is a must to use zip() function in the program, which I have not properly used yet.
I have made a program that does the general task successfully, but I can't figure out a solution that would use a zipped list. Could anyone help me with this? I have an idea that I could use the zipped list "q" that I have created within the map() function, but I don't know how.
Here is my program:
def transform(s1, s2):
i = 0
s = s1.split(' ')
d = s2.split(' ')
while i < len(s):
try:
s[i] = int(s[i])
d[i] = int(d[i])
i += 1
except ValueError:
break
print(s, d)
q = list(zip(s, d))
print(q)
final = list(map(lambda x, y: x * y, s, d))
return final
def main():
print(transform("1 5 3", "2 6 -1"))
if __name__ == "__main__":
main()
Thank you in advance to anyone that helps!
Upvotes: 3
Views: 416
Reputation: 46921
this should do what you want:
def transform(a, b):
return [int(i) * int(j) for i, j in zip(a.split(), b.split())]
a = "1 5 3"
b = "2 6 -1"
print(transform(a, b)) # [2, 30, -3]
the use of split
and zip
should be straightforward. then a list comprehension creates the list.
Upvotes: 3
Reputation: 2607
try this out
item1, item2 = "1 5 3", "2 6 -1"
def transform(i1, i2):
return [int(x) * int(y) for x, y in zip(i1.split(" "), i2.split(" "))]
print(transform(item1, item2))
Upvotes: 1
Reputation: 54168
To easily transform one string into a list of string you use map
s = "1 2 3"
list(map(int, s.split()))
> [1, 2, 3]
Then you zip the 2 lists
zip(map(int, s1.split()), map(int, s2.split()))
> [(1, 2), (5, 6), (3, -1)]`
Finally you want to apply lambda x: x[0] * x[1]
to each pair, or operator.mul(x[0], x[1])
from operator import mul
def transform(s1, s2):
return list(map(lambda x: mul(*x), zip(map(int, s1.split()), map(int, s2.split()))))
Upvotes: 2
Reputation: 16172
s1 = '1 5 3'
s2 = '2 6 -1'
def transform(s1, s2):
return [x*y for x,y in zip([int(x) for x in s1.split()],
[int(x) for x in s2.split()])]
transform(s1,s2)
Output
[2, 30, -3]
Upvotes: 1