python - One-liner to remove duplicates, keep ordering of list -
this question has answer here:
i have following list:
['herb', 'alec', 'herb', 'don']
i want remove duplicates while keeping order, :
['herb', 'alec', 'don']
here how verbosely:
l_new = [] item in l_old: if item not in l_new: l_new.append(item)
is there way in single line?
you use ordereddict
, suggest sticking for-loop.
>>> collections import ordereddict >>> data = ['herb', 'alec', 'herb', 'don'] >>> list(ordereddict.fromkeys(data)) ['herb', 'alec', 'don']
just reiterate: seriously suggest sticking for-loop approach, , use set
keep track of seen items:
>>> data = ['herb', 'alec', 'herb', 'don'] >>> seen = set() >>> unique_data = [] >>> x in data: ... if x not in seen: ... unique_data.append(x) ... seen.add(x) ... >>> unique_data ['herb', 'alec', 'don']
and in case want wacky (seriously don't this):
>>> [t[0] t in sorted(dict(zip(reversed(data), range(len(data), -1, -1))).items(), key=lambda t:t[1])] ['herb', 'alec', 'don']
Comments
Post a Comment