Reputation: 143
If a have a list like this:
[['welcome','a1'],['welcome','a1'],['hello','a2'],['hello','a3']]
and I want to return something like this:
[['welcome','a1', 2],['hello','a2', 1],['hello','a3', 1]]
If the same pair of strings in a sublist is encountered, increment the count
What I have so far:
counter = 0
for i in mylist:
counter += 1
if i[0]== i[0]:
if i[1] == i[1]:
counter -= 1
ouptut.append([mylist, counter])
I'm new at this and I appreciate your help!
Upvotes: 0
Views: 173
Reputation: 250931
Use a set
here to get only unique items:
>>> lis = [['welcome','a1'],['welcome','a1'],['hello','a2'],['hello','a3']]
>>> [list(x) + [1] for x in set(map(tuple, lis))]
>>> [['welcome', 'a1', 1], ['hello', 'a3', 1], ['hello', 'a2', 1]]
Explanation:
Set always returns unique items from an iterable or iterator, but as sets can only contain immutable item so you should convert them to a tuple first. A verbose version of the above code, only difference is that will also preserve the original or
>>> lis = [['welcome','a1'],['welcome','a1'],['hello','a2'],['hello','a3']]
>>> s = set()
>>> for item in lis:
... tup = tuple(item) #covert to tuple
... s.add(tup)
>>> s
set([('welcome', 'a1'), ('hello', 'a3'), ('hello', 'a2')])
Now use a list comprehension to get the expected output:
>>> [list(item) + [1] for item in s]
[['welcome', 'a1', 1], ['hello', 'a3', 1], ['hello', 'a2', 1]]
If the order of items matter(sets
don't preserve order), then use this:
>>> seen = set()
>>> ans = []
>>> for item in lis:
... tup = tuple(item)
... if tup not in seen:
... ans.append(item + [1])
... seen.add(tup)
...
>>> ans
[['welcome', 'a1', 1], ['hello', 'a2', 1], ['hello', 'a3', 1]]
I am not sure what's the point of using 1
here.
Upvotes: 1