Reputation: 1440
I have 2 lists of strings:
['Tipo de fertilizante',
'N',
'P2O5',
'K2O',
'S',
'CaO',
'MgO',
'Zn',
'Solubilidad g/100cc H2O',
'Precio (€/100 kg)',
'€/UF (N)',
'€/UF (P2O5)',
'€/UF (K2O)',
'€/UF (S)',
'€/UF (CaO)',
'€/UF (MgO)',
'JERARQUIA - (N)',
'JERARQUIA - (P2O5)',
'JERARQUIA - (K2O)',
'JERARQUIA - (S)',
'JERARQUIA - (CaO)',
'JERARQUIA - (MgO)',
'Abono']
and this is second one:
['JERARQUIA - (N)',
'JERARQUIA - (P2O5)',
'JERARQUIA - (K2O)',
'JERARQUIA - (S)',
'JERARQUIA - (CaO)',
'JERARQUIA - (MgO)']
I want to get elements of the first one that are contained in the elements of the second one so the desired result would be:
['N',
'P2O5',
'K2O',
'S',
'CaO',
'MgO',
'JERARQUIA - (N)',
'JERARQUIA - (P2O5)',
'JERARQUIA - (K2O)',
'JERARQUIA - (S)',
'JERARQUIA - (CaO)',
'JERARQUIA - (MgO)',]
I've looked into this answer and this is what i've tried:
[s for s in list_1 if any(i in s for i in list_2)]
but the result i get is:
['JERARQUIA - (N)',
'JERARQUIA - (P2O5)',
'JERARQUIA - (K2O)',
'JERARQUIA - (S)',
'JERARQUIA - (CaO)',
'JERARQUIA - (MgO)']
This is not what i want. After a lot of back and fourth with this, i still don't get how I can achieve the result I need.
How can i do this?
Thank you very much in advance.
Upvotes: 0
Views: 192
Reputation:
You can do it by nested for loops. It will make the programme a bit lengthy, but it will give u a surety that it will work.
list_3 = []
for i in list_1:
for j in list_2:
if i == j:
list_3.append(i)
Do try it this way.
Upvotes: 1
Reputation: 10624
Try this instead:
[s for s in list_1 if any(s in i for i in list_2)]
(explanation: we check for s in i instead of i in s in your example, that makes the difference in the result)
Upvotes: 5