Home > Net >  Create new lists looping through two lists
Create new lists looping through two lists

Time:02-16

Using two different lists A and B trying to create new lists as follows:

  1. Total number of new lists are equal to the total number of elements in list B.

  2. Each new column contains the items which result from multiplying elements in list A against elements In list B

A = [1, 2, 3, 4, 5]
B = [3, 4, 7] # list B has 3 elements, therefore 3 new lists are required

The lists would look like:

new_list1 = [3, 6, 9, 12, 15]
new_list2 = [4, 8, 12, 16, 20]
new_list3 = [7, 14, 21, 28, 35]

With the following loop, I see that I am returning the right values but can't group into list/dictionary as above.

list_dict = {}
for j in B:
    for k in A:
        list_dict = k * j
        print(list_dict)

CodePudding user response:

Fancy one-liner:

C = [list(map(lambda x: x * b, A)) for b in B]

Translated to loops:

C = []
for b in B:
    new_list = []
    for a in A:
        new_list.append(b * a)
    C.append(new_list)

Output:

[
  [3, 6, 9, 12, 15],
  [4, 8, 12, 16, 20], 
  [7, 14, 21, 28, 35]
]

CodePudding user response:

In your code, you need to store the results to a list and store that list into the dict:

list_dict = {}
for j in B:
    list_ = []
    for k in A:
        list_.append(k * j)
    list_dict[j] = list_

Output:

{3: [3, 6, 9, 12, 15], 4: [4, 8, 12, 16, 20], 7: [7, 14, 21, 28, 35]}

Or you could use a nested list comprehension:

new_list1, new_list2, new_list3 = [[a*b for a in A] for b in B]

CodePudding user response:

A = [1, 2, 3, 4, 5]
B = [3, 4, 7]
for i in B:
    list=[]
    for j in A:
       list.append(i*j)
    print(list)
output:-
[3, 6, 9, 12, 15]
[4, 8, 12, 16, 20]
[7, 14, 21, 28, 35]
  • Related