-2
all_combination = [[['a', 'b'], ['c', 'd']], [['e', 'f'], ['g', 'h']], [['c', 'd'], ['a', 'b']]]

assume that, [['a', 'b'], ['c', 'd']] = [['c', 'd'], ['a', 'b']] I want to remove the duplicate list from list but the order doesn't matter. and more thing i need a if condition that checks that both [['a', 'b'], ['c', 'd']] is equal to [['c', 'd'], ['a', 'b']].

This is my code i have tried so far.

all_combination = [[['a', 'b'], ['c', 'd']], [['e', 'f'], ['g', 'h']], [['c', 'd'], ['a', 'b']]]

unique = []
new = []
status = False
for i in all_combination:
    for j in i:
        for k in range(len(all_combination)):
            l = k+1
            for m in range(l, len(i)):
                if j == all_combination[k][m]:
                    unique.append(i)
print(new)

Expected Answer:

[[['a', 'b'], ['c', 'd']], [['e', 'f'], ['g', 'h']]]

or

[[['e', 'f'], ['g', 'h']], [['c', 'd'], ['a', 'b']]]

5 Answers5

1

Something like this?

list2 = [e for e in list1 if set(e) == {"a", "b"}]

Comparison between sets is independent of order.

Thomas
  • 174,939
  • 50
  • 355
  • 478
1

use set

sets don't care about the order

but they also don't care about the count

list1 = [["a","b"], ["c","d"], ["b","a"]]
list1 = [set(i) for i in list1]
ret = [list(i) for i in list1 if list1.count(i) ==1 ]
print (ret)
Kuldeep Singh Sidhu
  • 3,748
  • 2
  • 12
  • 22
1

To remove the duplicates you can do this (independent of order):

list1 = [["a","b"], ["c","d"], ["b","a"]]

uniques = set([frozenset(x) for x in list1])
uniques = [list(x) for x in uniques]

one line version

uniques = [list(x) for x in set([frozenset(x) for x in list1])]
Fredrik Nilsson
  • 549
  • 4
  • 13
1

You can also use collections.Counter:

from collections import Counter

list1 = [["a", "b"], ["c", "d"], ["b", "a"]]

list1_counter = Counter([frozenset(sub_list1) for sub_list1 in list])
list2 = []

for sub_list1 in list1:
    if list1_counter[frozenset(sub_list1)] == 1:
        list2.append(sub_list1)

list2 after this would equal [["c", "d"]].

list2 also preserves the order of the lists within list1.

Mario Ishac
  • 5,060
  • 3
  • 21
  • 52
1

Try this:

all_combination = [[['a', 'b'], ['c', 'd']], [['e', 'f'], ['g', 'h']], [['c', 'd'], ['a', 'b']]]

tmp = []
for data_list in all_combination:
    for data in data_list:
        if data not in tmp:
            tmp = tmp + [data]

print(tmp)

result = [['a', 'b'], ['c', 'd'], ['e', 'f'], ['g', 'h']]

dhentris
  • 198
  • 1
  • 2
  • 10