Search code examples
python-3.xlist-comprehension

How to convert loop to shortest list comprehension form?


I'm trying to get the shortest code to obtaina list of unique parameters (in order of appearence). These parameters are to the left of each parameter = something. I was able to build the below loop that works and stores in h the parameters

data = [
    'B = 3', 
    'T = 0', 
    'N = 5', 
    'V = 2', 
    'N = 1', 
    'V = 4',
    'B = 7', 
    'T = 2',
]

h = []
for d in data:
    el = d.split("=", 1)[0].strip()
    if el not in h:
        h.append(el)

>>> h
['B', 'T', 'N', 'V']

Then, I'd like to convert this in list comprehension and this works but I think there would be a way to write it even shorter without repeat the part d.split("=", 1)[0].strip() twice.

h = []
[h.append(d.split("=", 1)[0].strip()) for d in data if d.split("=", 1)[0].strip() not in h ]

I've tried this but doesn't seem to be the correct syntax.

h = []
[el = d.split("=", 1)[0].strip() h.append(el) for d in data if el not in h ]

Solution

  • While preserving order (and assuming you really only want the first character):

    list(dict.fromkeys(s[0] for s in data))
    

    Or to get the first set of characters before a space:

    list(dict.fromkeys([s.split()[0] for s in data]))
    

    You could also get fancy with this using map and operator.itemgetter

    from operator import itemgetter
    
    list(dict.fromkeys(map(itemgetter(0), map(split, data))))