Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I reorganize a list back with the help of a dict

Tags:

python

I have the following code:

list1 = [('a', 0), ('b', 100), ('c', 200), ('d', 300), ('e', 400), ('f', 500)]
list2 = [[0, 200, 400], [100, 300, 500]]

list2 just basically reorganizes the numbers into teams, the 2 sublists.

My list3 would then be:

list3 = [['a', 'c', 'e'], ['b', 'd', 'f']]

So by looking up the values in list2 in list1, what code do I need to produce list3?

This is also valid:

list1 = [('a', 0), ('b', 0), ('c', 0), ('d', 0), ('e', 0), ('f', 0)]
list2 = [[0, 0, 0], [0, 0, 0]]

It would give:

list3 = [['a', 'b', 'c'], ['d', 'e', 'f']]

So basically 'a' and 'f' could have the same value but they can only return once in list3

like image 556
hduu2929 Avatar asked May 08 '20 19:05

hduu2929


1 Answers

A possibility is to use collections.defaultdict with collections.deque:

from collections import defaultdict, deque
def to_num(a, b):
  d = defaultdict(deque)
  for j, k in a:
     d[k].append(j)
  return [[d[l].popleft() for l in i] for i in b]

list1 = [('a', 0), ('b', 100), ('c', 200), ('d', 300), ('e', 400), ('f', 500)]
list2 = [[0, 200, 400], [100, 300, 500]]
print(to_num(list1, list2))

Output:

[['a', 'c', 'e'], ['b', 'd', 'f']]

With your second test case:

list1 = [('a', 0), ('b', 0), ('c', 0), ('d', 0), ('e', 0), ('f', 0)]
list2 = [[0, 0, 0], [0, 0, 0]]
print(to_num(list1, list2))

Output:

[['a', 'b', 'c'], ['d', 'e', 'f']]
like image 77
Ajax1234 Avatar answered Oct 03 '22 19:10

Ajax1234