Home > database >  Python list withing list distinct elements
Python list withing list distinct elements

Time:02-06

I have a list that looks like this:

a = [[99 , 2],[2,99]]

My objective is to get a list that has one of the elements because they are similar combinations:

so I need another list b that is either:

b = [[99,2]]

or

b= [[2,99]]

How do I go about it in the most efficient manner without any libraries, answers with libraries are also appreciated since I would wanna know what are the stuffs already out there to ease my pain with learning how to code.

Thank you

CodePudding user response:

There might be many different ways to do it, but one option is to use frozenset in set:

a = [[99,2],[1,2,3],[2,99],[2,3,1]]
b = set(frozenset(x) for x in a)
print(b) # {frozenset({1, 2, 3}), frozenset({2, 99})}
b = [list(x) for x in b]
print(b) # [[1, 2, 3], [2, 99]]

Another option is to use (sorted) tuples to represent the "uniquified" elements:

b = set(tuple(sorted(x)) for x in a)

However, frozenset seems faster: Hashing frozenset versus tuple of sorted

CodePudding user response:

I can give you an answer using libraries. random is part of the python standard library (you already have it installed if you have python), so depending on why you don't want to use libraries, this might work.

import random

a = [[99 , 2],[2,99]]
b = random.choice(a)

b will be a list that has exactly one of the elements of list a. If you need b to be a list of lists, modify it like so:

import random

a = [[99 , 2],[2,99]]
b = [random.choice(a)]
  •  Tags:  
  • Related