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'
CodePudding user response:
Well this is one way to do it, but this question may have cleaner solutions as well:
L = ['A','B','C']
L2 = ['A', 'B', ('B', 'A'), 'C']
answer = []
for l2 in L2:
if len(l2) == 1:
if l2 in L:
answer.append(l2)
elif l2[0] in L:
answer.append(l2)
if l2[0] in answer:
answer.remove(l2[0])
print(answer)
['A', ('B', 'A'), 'C']
CodePudding user response:
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']