-3

This is my list:

nab = ['b', 'b', 'a', 'b', 'b', 'b', 'a', 'a', 'a', 'a']

I want to combine the same elements which are adjacent into another list, and if they are not the same, just return the element itself. The output that I am looking for is:

['b', 'a', 'b', 'a'] 

I mean: two 'b' ---> 'b', one 'a' ---> 'a', three 'b' ---> 'b', four 'a' ---> 'a' I want to know the length of the new list.

  • 4
    So, have you done anything yourself yet? – Roman Ferenets Dec 18 '20 at 22:54
  • 1
    Please repeat [on topic](https://stackoverflow.com/help/on-topic) and [how to ask](https://stackoverflow.com/help/how-to-ask) from the [intro tour](https://stackoverflow.com/tour). “Show me how to solve this coding problem” is not a Stack Overflow issue. We expect you to make an honest attempt, and *then* ask a *specific* question about your algorithm or technique. Stack Overflow is not intended to replace existing documentation and tutorials. – Prune Dec 18 '20 at 22:59
  • Also see Stack Overflow guidance on [homework](https://meta.stackoverflow.com/questions/334822/how-do-i-ask-and-answer-homework-questions). Simply dumping your assignment here is unacceptable. – Prune Dec 18 '20 at 22:59
  • `itertools.groupby` creates subiterators for consecutive keys in a collection. You just need the first value of each of the subiterators. `[next(grp).upper() for _, grp in itertools.groupby(n)]`. – tdelaney Dec 18 '20 at 23:07

1 Answers1

2

Thank you so much @tdelaney, I did it as below:

import itertools  
nab = ['B', 'B', 'A', 'B', 'B', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'A', 'A', 'B', 'B', 'A', 'A', 'B', 'A', 'B', 'B', 'B', 'B', 'A']
U = []
key_func = lambda x: x[0]  
for key, group in itertools.groupby(nab, key_func): 
    U.append(list(group))
print(U)
print(len(U))

Output: 
[['B', 'B'], ['A'], ['B', 'B'], ['A', 'A', 'A', 'A'], ['B', 'B', 'B'], ['A', 'A'], ['B', 'B'], ['A', 'A'], ['B'], ['A'], ['B', 'B', 'B', 'B'], ['A']]