Home > Net >  make two new lists from the current list
make two new lists from the current list

Time:12-09

I have a list name list1: list1 = [['DC1', 'C4'], ['DC1', 'C5'], ['DC3', 'C1'], ['DC3', 'C2'], ['DC3', 'C3']]

I want to make two new lists:

list1_1 = ['DC1', 'C4', 'C5']

list1_2 = ['DC3', 'C1', 'C2', 'C3']

can anyone please show me how to do? thank you.

CodePudding user response:

this can solve your problem. note: this is not an optimized one

yourlist = [['DC1', 'C4'], ['DC1', 'C5'], ['DC3', 'C1'], ['DC3', 'C2'], ['DC3', 'C3']]

temp_dict = {}
for i in yourlist:
    if i[0] not in temp_dict:
        temp_dict.update({i[0]:[i[1]]})
    else:
        temp_dict[i[0]].append(i[1])


final_list =[]
for i,j in temp_dict.items():
    temp_list =[i]
    for k in j:
        temp_list.append(k)
    final_list.append(temp_list)

list1_1 = final_list[0]
list1_2 = final_list[1]

Output:

list1_1

['DC1', 'C4', 'C5']

list1_2

['DC3', 'C1', 'C2', 'C3']

CodePudding user response:

Building on Tamil Selvan's answer, but using a defaultdict for simplicity and list concatenation instead of appends for the big list.

from collections import defaultdict
list1 = [['DC1', 'C4'], ['DC1', 'C5'], ['DC3', 'C1'], ['DC3', 'C2'], ['DC3', 'C3']]

# First we create a dict containing the left terms as keys and the right terms as values.
d = defaultdict(list)
for (key, value) in list1:
    d[key].append(value)
print(d)
# {'DC1': ['C4', 'C5'],
#  'DC3': ['C1', 'C2', 'C3']}

# Then for each key, we create a list of values with the key as first item.
lists = []
for key, values in d.items():
    sublist = [key, *values]
    lists.append(sublist)
print(lists)
# [['DC1', 'C4', 'C5'],
#  ['DC3', 'C1', 'C2', 'C3']]

# Finally, you can easily take the sublist that you want.
list1_1, list1_2  = lists
  • Related