epic_fil
epic_fil

Reputation: 679

Python to filter a comma-separated list on another csv list

I have two strings:

s1 = "Brendon, Melissa, Jason, , McGuirk" #the gauranteed string in format "x, y, z"
s2 = "brandon,melissa,jxz  ,paula,coach" #the messy string

and would like to create a Python (2.7) list that uses the value in l1 if it exists, otherwise pass through the value in l2. I have working code, but even with the list comprehensions, I feel like there may be a more Pythonic way of doing this. Any ideas what that might be?

l1 = [x.strip() for x in s1.split(',')]
l2 = [x.strip() for x in s2.split(',')]
f = lambda s: s[1] if s[1] else s[0]
final = [f(x) for x in zip(l2, l1)]

The list "final" now contains:

['Brendon', 'Melissa', 'Jason', 'paula', 'McGuirk']

Which is correct.

------- edit So, looking at Jon's answer below, a or b seems like the simplest, most readable approach. I moved the string cleaning to a small function, and ended up with this. Any further improvements to make?

trim_csv = lambda csv: [s.strip() for s in csv.split(',')]
print [a or b for a, b in zip(trim_csv(s1), trim_csv(s2))]

Upvotes: 3

Views: 1092

Answers (2)

Jon Clements
Jon Clements

Reputation: 142176

Works for your example

s1 = "Brendon, Melissa, Jason, , McGuirk"
s2 = "brandon, melissa, jxz, paula, coach"

print [a or b for a, b in zip(s1.split(', '), s2.split(', '))]

Slightly more generic one that can be adapated:

import re
from itertools import izip_longest, ifilter, imap

s1 = "Brendon, Melissa, Jason, , McGuirk"
s2 = "brandon, melissa, jxz, paula, coach"


def take_first_not_empty(*args):
    splitter = re.compile(r'\s*?,\s*').split
    words = imap(splitter, args)
    return [next(ifilter(None, vals), '') for vals in izip_longest(*words, fillvalue='')]

Upvotes: 6

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251001

Something like this?

>>> s1 = "Brendon, Melissa, Jason, , McGuirk"
>>> s2 = "brandon, melissa, jxz, paula, coach"
>>> [x if x else y  for x,y in zip( s1.split(', '),s2.split(', '))]
['Brendon', 'Melissa', 'Jason', 'paula', 'McGuirk']

Upvotes: 2

Related Questions