Reputation: 79
I'm trying to create a list of unique items from a list of lists by selecting one item from each list, and if an item in a list is already in the unique item list, then select the second unique item and so on.See list and my attempt below;
mylist=`[[1,2,3],[1,2,3],[1,2,3]]`
def unique(lists):
uniquelst=[]
for _lst in lists:
if _lst[0] not in uniquelst:
uniquelst.append(_lst[0])
else:
uniquelst.append(_lst[1])
return uniquelst
my output: [1, 2, 2]
Expected output: [1, 2, 3]
Only one item to be selected from each list, hence the appropriate solution should be able to produce the same result for this example [[1, 4, 3], [1, 2, 5], [1, 2, 3]]
Any ideas? thanks.
Upvotes: 2
Views: 152
Reputation: 3226
With the restrictions you mentioned this code should work -
def unique(lists):
uniquelst = []
for lst in lists:
for elem in lst:
if elem not in uniquelst:
uniquelst.append(elem)
break
return uniquelst
The second loop iterates over elements of the inner list and check if they are already present in uniquelst
. In case they are not present, add the element and break from inner loop.
One thing I forgot to mention is that this code assumes the elements of inner list are in sorted order. If that is not the case, please sort inner list using sorted()
or sort()
before the second loop
Upvotes: 4
Reputation: 92854
With set object and itertools.chain(iterables) function:
import itertools
mylist = [[1,2,3],[1,2,3],[1,2,3]]
result = set(itertools.chain(*mylist))
print(list(result))
The output:
[1, 2, 3]
Upvotes: 5
Reputation: 679
flat_list = [item for sublist in mylist for item in sublist]
print(list(set(flat_list)))
Upvotes: 5
Reputation: 821
newlist = []
for l in mylist:
newlist = newlist + l
return list(set(newlist))
Does this help you?
Upvotes: 1