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!
you can use a list comprehension:
from functools import reduce
from operator import mul
[reduce(mul, t, 1) for t in my_list]
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]
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.