Creating two separate "lists of lists" out of "list" & "list of lists"

Viewed 639

I haven't found a similar question with a solution here, so I'll ask your help.

There are 2 lists, one of which is list of lists:

categories = ['APPLE', 'ORANGE', 'BANANA']
test_results = [['17.0', '12.0'], ['21.0', '15.0'], ['7.0', '6.0']]

As a final result I would like to split it by 2 separate lists of lists:

[['APPLE','17.0']['ORANGE','21.0']['BANANA','7.0']]
[['APPLE','12.0']['ORANGE','15.0']['BANANA','6.0']]

I tried to create loops but I have nothing to share. Any ideas are appreciated.

6 Answers

This is a simple answer. Hope its what you were looking for.

categories = ['APPLE', 'ORANGE', 'BANANA']
test_results = [['17.0', '12.0'], ['21.0', '15.0'], ['7.0', '6.0']]

# Declare 2 lists
list1 = []
list2 = []

for category, results in zip(categories, test_results):
    # Append to each list
    list1.append([category, results[0]])
    list2.append([category, results[1]])

# Print lists
print(list1)
print(list2)

You can do it simply using list traversal and choosing element at index from first list and values from second list:

l1 = []
l2 = []
for i, values in enumerate(test_results):
    l1.append([categories[i], values[0]])
    l2.append([categories[i], values[1]])

print(l1)
print(l2)

# Output
# [['APPLE', '17.0'], ['ORANGE', '21.0'], ['BANANA', '7.0']]
# [['APPLE', '12.0'], ['ORANGE', '15.0'], ['BANANA', '6.0']]

You can use some Python built-in functions.

for i in range(len(test_results[0])):
    print(list(map(list, zip(categories, map(lambda x: x[i], test_results)))))

list comprehension:

categories = ['APPLE', 'ORANGE', 'BANANA']
test_results = [['17.0', '12.0'], ['21.0', '15.0'], ['7.0', '6.0']]

total_list = [[[category, num] for category, num in zip(categories, i)] for i in zip(*test_results)]
l1, l2 = total_list # due to there are only two sub-list in total list.
print(l1, l2, total_list, sep="\n")

Another way of doing this:

from itertools import chain
test_results = list(chain.from_iterable(test_results))
l1, l2 = list(map(list,zip(categories, test_results[::2]))), list(map(list,zip(categories, test_results[1::2])))

output:

[['APPLE', '17.0'], ['ORANGE', '21.0'], ['BANANA', '7.0']]
[['APPLE', '12.0'], ['ORANGE', '15.0'], ['BANANA', '6.0']]

Another more generalizable version:

from itertools import chain, repeat
test_results = list(chain.from_iterable(test_results))
categories = list(chain.from_iterable(repeat(x,2) for x in categories))
l = list(map(list,zip(categories, test_results)))
l1, l2 = l[::2], l[1::2]
categories = ['APPLE', 'ORANGE', 'BANANA']
test_results = [['17.0', '12.0'], ['21.0', '15.0'], ['7.0', '6.0']]
l = []
d=0
for i in range(len(categories)):
    k = len(test_results[0])
    for j in range(len(categories)):
        l.append([categories[j],test_results[j][d]])
    print(l)
    l=[]
    d+=1
    if d==k:
        break
Related