0

I really want to know how to extract all the element from two lists and multiply each other. For example, if there are two lists

A=[1,3,5,7,9]
B=[2,4,6,8]

I want to do 1X2, 1X4, 1X6, 1x8, 3x2... etc. One element from A X one element from B. I tried to use zip but because of length difference, I couldn't get right answers.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Ellie
  • 45
  • 1
  • 2
  • 3
    You would want to do something similar to this: https://stackoverflow.com/questions/12935194/combinations-between-two-lists – gmpatzer Jan 08 '18 at 01:57
  • 2
    "I want to do 1X2, 1X4, 1X6, 1x8, 3x2... etc." that is not random. It looks like a Cartesian mesh of the two lists. Is that what you want or do you actually want a **random** sample of the two lists? – James Jan 08 '18 at 02:21

3 Answers3

10

SInce your question seems to want the cartesian product between two lists, you can use itertools.product to bind every element from A with every element from B:

>>> from itertools import product
>>> A = [1,3,5,7,9]
>>> B = [2,4,6,8]
>>> list(product(A, B))
[(1, 2), (1, 4), (1, 6), (1, 8), (3, 2), (3, 4), (3, 6), (3, 8), (5, 2), (5, 4), (5, 6), (5, 8), (7, 2), (7, 4), (7, 6), (7, 8), (9, 2), (9, 4), (9, 6), (9, 8)]

Then if you want to multiply the the two elements in each tuple, you can do this:

>>> [x * y for x, y in product(A, B)]
[2, 4, 6, 8, 6, 12, 18, 24, 10, 20, 30, 40, 14, 28, 42, 56, 18, 36, 54, 72]
RoadRunner
  • 25,803
  • 6
  • 42
  • 75
0

To get a random value from a list, you can do something similar to the following:

import random
lst = [10,20,30]
x = random.choice(lst)

Importing the random library gives you access to a ton of random generation tools. Per the random library documentation (https://docs.python.org/3/library/random.html), random.choice(seq) returns a random element from a non-empty sequence, such as a list. Thus, the code above randomly selects an element from lst and assigns that value to the variable x.

I don't want to give the solution away until you've tried using the random library, so I'll let you figure out how to use the information above.

Jacob Rodal
  • 620
  • 1
  • 6
  • 12
0

You can use for loops:

Operation for each item in A with each item in B:

A=[1,3,5,7,9]
B=[2,4,6,8]

C = [] #Create an empty list
for i in A: #iter each element in A
    for j in B: #iter each element in B
        mult = i * j
        C.append(mult) #Append the result in the list C
print(C)

Operation with a random item in A with each item in B:

import numpy as np

A=[1,3,5,7,9]
B=[2,4,6,8]

C = [] #Create an empty list
for i in A: #iter each element in A
    i = np.random.randint(len(A)) #Chose a random number from A
    for j in B: #iter each element in B
        mult = A[i] * j #Multiply a random number from A with each element in B
        C.append(mult) #Append the result in the list C
print(C)
virtualdvid
  • 2,323
  • 3
  • 14
  • 32