Issue
I have a list below:
list = [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
How do I return a list containing the products of the elements in the tuples, ie.:
[1, 2, 3, 2, 4, 6, 3, 6, 9]
where
1*1 = 1 is the 1st element in the new list
1*2 = 2 is the 2nd element in the new list
1*3 = 3 is the 3rd element in the new list
2*1 = 2 is the 4th element in the new list
2*2 = 4 is the 5th element in the new list
etc.
A way to do this in a list comprehension would be great. Thanks!
Solution
No need to use libraries, a simple list comprehension will do that just fine:
lst = [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
products = [a*b for a,b in lst]
# [1, 2, 3, 2, 4, 6, 3, 6, 9]
Answered By - Alain T. Answer Checked By - Pedro (PHPFixing Volunteer)
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.