I have a list like this:
list_values=[("10",1),("10",2),("16",2),("16",1),("15",1)]
I want the result as :
Result=[("10",1),("16",2),("15",1)]
can anyone help me?
I have a list like this:
list_values=[("10",1),("10",2),("16",2),("16",1),("15",1)]
I want the result as :
Result=[("10",1),("16",2),("15",1)]
can anyone help me?
Looks very much like How do you remove duplicates from a list whilst preserving order?, but just "carrying" the second element, not including it in the hash/comparison/whatever.
Two ways of doing this:
Either use a marker set to note down the occurrences of the first values:
list_values=[("10",1),("10",2),("16",2),("16",1),("15",1)]
seen = set()
seen_add = seen.add
result = []
for k,v in list_values:
if k not in seen:
seen_add(k)
result.append([k,v])
print(result)
yields (preserves order):
[['10', 1], ['16', 2], ['15', 1]]
or use a dictionary on reversed items to keep the first value only:
result = list(dict(reversed(list_values)).items())
print(result)
yields (won't preserve order):
[('15', 1), ('10', 1), ('16', 2)]
Using collections.OrderedDict
and reversing twice allows to preserve order too
import collections
result = list(reversed(list(collections.OrderedDict(reversed(list_values)).items())))
results in:
[('10', 1), ('16', 2), ('15', 1)]
That, unless Python 3.6+ is used, where dictionaries retain insertion order. From python 3.5 you can remove some forced list conversions so that will work:
list(reversed(collections.OrderedDict(reversed(list_values)).items()))
very bad that the OP not try or not show us some solution, but here the simple one:
list_values = [("10",1),("10",2),("16",2),("16",1),("15",1)]
Result = list(dict(reversed(list_values)).items())
print(Result)
will give you:
[('15', 1), ('16', 2), ('10', 1)]