0
#orignal list
list_one = [['a','b'],['a','c'],['b','c'],['b','a']]
li=[]
for i in list_one:
    for j in list_one:
        if i[0] == j[1] and j[0] == i[1]:
            li.append([i,j])
print(li)

#[[['a', 'b'], ['b', 'a']], [['b', 'a'], ['a', 'b']]]

I need the output to be [a,b] only the a and b can vary depending on the condition like a can be apple or anything

StupidWolf
  • 45,075
  • 17
  • 40
  • 72
  • 1
    Does this answer your question? [finding duplicates in a list of lists](https://stackoverflow.com/questions/19811418/finding-duplicates-in-a-list-of-lists) – Carlo Zanocco Aug 29 '20 at 16:44
  • @CarloZanocco "... if the elements of the list are not in order" – Thierry Lathuille Aug 29 '20 at 16:45
  • @ThierryLathuille Why not order it? He don't ask the question with the constraint to not order the list. He just say they are not in order. – Carlo Zanocco Aug 29 '20 at 16:47
  • 1
    @CarloZanocco I don't see any answer in the duplicate you suggest that can answer this question... – Thierry Lathuille Aug 29 '20 at 16:50
  • Considering the @ThierryLathuille maybe you want to preserve the order of the list so check [here](https://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-whilst-preserving-order) – Carlo Zanocco Aug 29 '20 at 16:51

3 Answers3

0

When considering a sublist, you only need to look for a duplicate in the queue of the list, beyond the current sublist. With minor changes to your code, you could do:

list_one = [['a','b'],['a','c'],['b','c'],['b','a']]
li=[]
for index, i in enumerate(list_one):
    for index2 in range(index+1, len(list_one)):
        j = list_one[index2]                
        if i[0] == j[1] and j[0] == i[1]:
            li.append([i,j])
print(li)
# [[['a', 'b'], ['b', 'a']]]
Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50
0

It seems you are looking for items which contain letters that have not been seen before. The simplest way to do this is by building a cache.

cache = set() # will contain all individual letters that have been seen
li = []
for item in list_one:
    if not any(letter in cache for letter in item):
        li.append(item)
    cache.update([letter for letter in item])
print(li)

[['a', 'b']]
RichieV
  • 5,103
  • 2
  • 11
  • 24
0

One way could be:

Sort the list, find the duplicate nested.

#orignal list
data = [['a','b'],['a','c'],['b','c'],['b','a']]
seen = []
data = [sorted(x) for x in data]
data = [x if x in seen else seen.append(x) for x in data]
print([x for x in data if x])

OUTPUT:

[['a', 'b']]
DirtyBit
  • 16,613
  • 4
  • 34
  • 55