Home > Mobile >  How to convert loop to shortest list comprehension form?
How to convert loop to shortest list comprehension form?

Time:09-30

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 ]

CodePudding user response:

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]))

CodePudding user response:

Try:

h = list(set(s.split()[0].strip() for s in data))
print(h)

Prints:

['N', 'V', 'B', 'T']
  • Related