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
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']]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With