There is a list
list = [1,1,1,2,3,4,2,2,2] It is necessary to "merge" neighboring elements to get
list = [1,2,3,4,2] How can I solve this problem?
There is a list
list = [1,1,1,2,3,4,2,2,2] It is necessary to "merge" neighboring elements to get
list = [1,2,3,4,2] How can I solve this problem?
The easiest way is to use groupby . It is intended for such cases - it returns an iterator with consecutive elements and their number.
from itertools import groupby old_list = [1,1,1,2,3,4,2,2,2] groupped = groupby(old_list) print([elem for elem, grouper in groupped ]) >>> [1, 2, 3, 4, 2] If you need to know the number of consecutive elements, you can do this:
for elem, grouper in groupped : print(elem, len(list(grouper))) >>> 1 3 >>> 2 1 >>> 3 1 >>> 4 1 >>> 2 3 uniq = map(itemgetter(0), groupby(list_)) - jfsThe simplest option for beginners:
list = [1,1,1,2,3,4,2,2,2] result = [] prev = None for a in list: if a != prev: result.append(a) prev = a print(result) But the variant with the same logic, but more complicated, with list generators:
list = [1,1,1,2,3,4,2,2,2] def gen(lst): prev = None for a in lst: if a != prev: prev = a yield a print([x for x in gen(list)]) Source: https://ru.stackoverflow.com/questions/543859/
All Articles