Home > Enterprise >  Is there a better way to sum an element to a list of different length?
Is there a better way to sum an element to a list of different length?

Time:09-21

Is there a better way to do this? Maybe with itertools or operator, or something else?

I'm currently doing this way.

main_tx = [100, 200]
add_tx = [1, 2, 3]

tx = []
for x in main_tx:
    for user_x in add_tx:
        t = x   user_x
        tx.append(t)
print(tx) #[101, 102, 103, 201, 202, 203]



CodePudding user response:

A list comprehension:

>>> [x   y for x in main_tx for y in add_tx]
[101, 102, 103, 104, 201, 202, 203, 204]
>>> 

CodePudding user response:

Yes, you definitely can use itertools with its product function which iterates the cartesian product of given iterables (two list objects in your case):

from itertools import product

main_tx = [100, 200]
add_tx = [1, 2, 3]

tx = []
for x, user_x in product(main_tx, add_tx):
    tx.append(x   user_x)

Now, you can do it more efficient and more pythonic using list comprehension:

tx = [x   user_x for x, user_x in product(main_tx, add_tx)]

Also, as mentioned in the comments by @don't talk just code, you can also do this:

tx = list(map(sum, product(main_tx, add_tx)))

Which would probably be the most efficient way to achieve the result

  • Related