Given pairs of items of form [(a,b),...] where (a,b) means a > b, for example:
[('best','better'),('best','good'),('better','good')] I would like to output a list of form:
['best','better','good'] This is very hard for some reason. Any thoughts?
Given pairs of items of form [(a,b),...] where (a,b) means a > b, for example:
[('best','better'),('best','good'),('better','good')] I would like to output a list of form:
['best','better','good'] This is very hard for some reason. Any thoughts?
Flatten it, remove the duplicates, and sort:
>>> i = [(1,2),(1,3),(1,4),(2,3),(2,4),(3,4)]
>>> sorted({x for s in i for x in s})
[1, 2, 3, 4]
While @TigerhawkT3 has already given you solution, this one would work for arbitrarily nested lists/tuples:
def flatten(seq):
for el in seq:
if isinstance(el, (tuple, list)):
yield from flatten(el)
else:
yield el
l = [(1,2),(1,3),(1,4),(2,3),(2,4),(3,4)]
unique = sorted({el for el in flatten(l)})
print(unique) # [1, 2, 3, 4]
def remove_duplicates(seq):
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))]
i = [(5,2),(1,3),(1,4),(2,3),(2,4),(3,4)]
i = remove_duplicates(list(x for s in i for x in s))
print(i) # prints [5, 2, 1, 3, 4]
j = [('excellent','good'),('excellent','great'),('great','good')]
j = remove_duplicates(list(x for s in j for x in s))
print(j) # prints ['excellent', 'good', 'great']
See reference: How do you remove duplicates from a list in whilst preserving order?
For explanation on the remove_duplicates()
function, see this stackoverflow post.
Isn't the following working in your case?
import itertools
lst = [(1,2),(1,3),(1,4),(2,3),(2,4),(3,4)]
final_list = sorted(set(itertools.chain(*lst)))
print(final_list)
Seems to work at least in the cases you've mentioned.