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

python nested list and string trimming in a for statement

Now, having a list of lists with 2 strings:

l1 = [['a', 'www.apple.com/a www.google.com www.yahoo.com'],
    ['b', 'www.apple.com/sm www.sashgh.com www.uensg.com'],
    ['c', 'www.apple.com/oths www.zhiut.com'],
    ['d', 'www.amazon.com www.toronto.com']]

I want to keep the first string, and get the ‘apple.com’ url in the 2nd string or if there is not ‘apple.com’ give a None (like the case in ‘d’):

l2 = [['a', 'www.apple.com/a'], 
    ['b', 'www.apple.com/sm'],
    ['c', 'www.apple.com/oths'],
    ['d', None]]

I tried 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

l2 = []
for l in l1:
    for url in l[1].split(' '):
        if 'apple.com' in url:
            l2.append([l[0], url])
            break
        else:
            l2.append([l[0], None])
            break

and the code now worked!

>Solution :

Since you’re only appending the first apple.com in the split strings in the second elements of the sublists, you could use next and a generator expression to extract the first apple.coms.

out = [[first, next((s for s in second.split() if 'apple.com' in s), None)] for first, second in l1]

Output:

[['a', 'www.apple.com/a'],
 ['b', 'www.apple.com/sm'],
 ['c', 'www.apple.com/oths'],
 ['d', None]]
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