Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

replace strings in unequal nested lists

I have an unequal nested list containing strings.

newlist=[['realoldbone', 'thenewhouse', 'oldking'],
         ['softhat', 'hatoldhat'],
         ['shirt', 'sweatshirt', 'myoldShirt']]

For two features say,

Features=["old","new"]

if the element in newlist contains an element of Features, I want to replace it with that element of Features. So, the final answer will be like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

newlist=[['old', 'new', 'old'],
     ['softhat', 'old'],
     ['shirt', 'sweatshirt', 'old']]

I can’t think of a way how I can achieve this. I tried using for j in i for i in newlist type of loops along with string matching but to no avail. So,
I appreciate your suggestions.

>Solution :

The simplest case would be to loop through the lists and modify if feature exists:

for feature in Features:
    for lst in newlist:
        for i, item in enumerate(lst):
            if feature in item:
                lst[i] = feature
print(newlist)

Output:

[['old', 'new', 'old'], ['softhat', 'old'], ['shirt', 'sweatshirt', 'old']]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading