Home > Mobile >  python nested list and string trimming in a for statement
python nested list and string trimming in a for statement

Time:03-28

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 :

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!

CodePudding user response:

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]]
  • Related