It's really childish to ask this question but really want an optimal solution for this. I have an array of string
("a1,a2", "a3,a4", "a2,a1", "a5,a3")
and I want to Display
("a1,a2", "a3,a4", "a5,a3")
i.e. the first string is in, its duplicates are omitted.
Note: the order of the elements must be preserved
Pynchia
11.7k5 gold badges37 silver badges49 bronze badges
asked Sep 9, 2019 at 8:20
-
3Also this is a tuple, not an array.AnsFourtyTwo– AnsFourtyTwo2019年09月09日 08:23:23 +00:00Commented Sep 9, 2019 at 8:23
-
Possible duplicate of Remove duplicates in a list while keeping its order (Python)Umair Ayub– Umair Ayub2019年09月09日 08:24:49 +00:00Commented Sep 9, 2019 at 8:24
2 Answers 2
This is one approach.
Ex:
data = ("a1,a2","a3,a4","a2,a1","a5,a3")
seen = set()
result = []
for i in data:
if ",".join(sorted(i.split(","))) not in seen:
result.append(i)
seen.add(i)
print(result)
Output:
['a1,a2', 'a3,a4', 'a5,a3']
answered Sep 9, 2019 at 8:23
-
the inner list (the one inside
set
) is unnecessaryPynchia– Pynchia2019年09月09日 08:28:24 +00:00Commented Sep 9, 2019 at 8:28 -
I forgot to add about the "order" in the question. Actually order is required. Thank you for the answer. will try the answer.Sharath Nayak– Sharath Nayak2019年09月09日 08:28:45 +00:00Commented Sep 9, 2019 at 8:28
-
@SharathNayak. Updated snippetRakesh– Rakesh2019年09月09日 08:32:09 +00:00Commented Sep 9, 2019 at 8:32
your data is in a variable called "data".
new_data = []
for example in data:
example2 = str(example.split(",")[1] + "," + example.split(",")[0])
if example in new_data or example2 in new_data:
continue
else:
new_data.append(example)
print(new_data)
If you want to store them in your original list, run this script.
data.clear()
data = new_data.copy()
answered Sep 9, 2019 at 8:37
lang-py