Stack Overflow Asked by HarrisAMA on November 4, 2021
I’m not sure if the title is a great explanation of what I’m trying to do so here is an example:
Array = ['orangutan', 'sun', 'tan']
I want to print:
'orangutan', 'sun'
I’ve tried looping through the array and looking to see if one item contains another item as followed:
for i in Array:
remove_duplicates = [x for x in Array if x in i]
But this hasn’t worked.
Any help would be greatly appreciated, thanks!
I've tried looping through the array and looking to see if one item contains another item as followed.
you were almost there:
list_ = []
Array = ['orangutan', 'sun', 'tan']
for i in Array:
list_.extend([x for x in Array if x in i and x != i])
print(list_)
output:
['tan']
Answered by Sai Sreenivas on November 4, 2021
The remove() method removes the first matching element (which is passed as an argument) from the list.
Answered by Sneha Patel on November 4, 2021
I assume that you have another array with the strings that you want to keep. If this is the case, you can loop and use .pop():
array=['orangutan', 'sun', 'tan']
other_array=['orangutan', 'sun']
for i in range(0,len(array)):
if array[i] not in other_array:
array.pop(i)
print(array)
array=['orangutan', 'sun']
Answered by Rorepio on November 4, 2021
You can do:
lst = ['orangutan', 'sun', 'tan']
print([x for i, x in enumerate(lst)
if not any(x in y for j, y in enumerate(lst) if i != j)])
Update:
It won't escape notice that I have arrived at essentially the same solution as Riccardo Bucco. But the tests are different here. For the equivalence of these two tests, see De Morgan's laws. The any
(i.e. a reduction of or
over the boolean inputs) gives the inverse of all
(i.e. reduction of and
) on the inverse of those inputs -- hence the not any(... in ...)
is equivalent to all(... not in ...)
.
In either case, iteration will stop at the first match: all
will stop iterating and return False
if it sees a false-like value, and any
will stop iterating and return True
if it sees a true-like value.
Answered by alani on November 4, 2021
Here is a possible solution:
result = [x
for i, x in enumerate(Array)
if all(x not in y for j, y in enumerate(Array) if i != j)]
Answered by Riccardo Bucco on November 4, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP