'How to reduce a List of element following a Logic in python?
I have Two list:
L = ['A','B','C']
L2 = ['A', 'B', ('B', 'A'), 'C']
I would create a single list with the following element:
L3 = ['A', ('B', 'A'), 'C']
Every time an element in the list L is present in more element in the L2 list I would pick the longest one. Important, Only if B Is at the first place of the tuple
I tried the following code: the following code
temp_length = 0
for d in L:
for d2 in L2:
if d in d2 and temp_length<len(d2):
temp_op = d
L3.append(temp_op)
But is not adding ('B','A') instead of 'B'
Solution 1:[1]
First, find the longest elements in L2 (according to the first sub-element match) and keep them in a dictionary using the matching sub-element as a key.
It's much faster than looking for elements in lists many times and repeat checking the shorter ones needlessly.
from typing import Dict, Iterable
l = ['A','B','C']
l2 = ['A', 'B', ('B', 'A'), 'C']
def keep_longest_elements(seq: Iterable) -> Dict:
res = {}
for el in seq:
if (exist_el := res.get(el)) is not None:
if exist_el[0] == el[0] and len(el) > len(exist_el):
res[exist_el[0]] = el
else:
res[el[0]] = el
return res
longest = keep_longest_elements(l2)
print(longest)
l3 = [longest[el] for el in l]
print(l3)
produces
{'A': 'A', 'B': ('B', 'A'), 'C': 'C'}
['A', ('B', 'A'), 'C']
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
