-1

I have a list that looks like this.

[6, 1, 1, 1, 5, 1, 7, 1, 7, 1, 7, 7, 7, 1, 7, 1, 1, 3, 1, 1, 1, 1]

There are some consecutive 1s in it.

After counting the number of consecutive 1s, I want to sum all the 1s and add 1 to each sum like this.

1,1,1,1 => 5
1,1,1 => 4
1,1 => 3
1 => 2

And then, I want to put them in each place where the consecutive 1 were.

[6, 4, 5, 2, 7, 2, 7, 2, 7, 7, 7, 2, 3, 5]

Finally, I want to change any numbers other than 1 to 1 without changing the bold text.

[1, 4, 1, 2, 1, 2, 1, 2, 1, 1, 1, 2, 1, 5]

How can I do this?

Any help will be greatly appreciated.

layperson
  • 59
  • 4
  • You don't ask for much, do you? It sure would be great to see what you actually tried, given that "help" implies effort from both sides and you have given _none_ – roganjosh Jan 02 '23 at 18:43
  • Welcome back to Stack Overflow. As a refresher, please read [ask]. Note well that this is **not a discussion forum**; we [cannot offer](https://meta.stackoverflow.com/questions/284236) "help", and [do not care about](https://meta.stackoverflow.com/questions/343721) "appreciation". We *do* want questions that are clear, specific and *focused* - i.e., which are **one** question at a time. If you can group up the consecutive identical numbers, the rest should follow naturally. If it doesn't, then you have separate questions about the rest of the logical steps. – Karl Knechtel Jan 02 '23 at 18:52
  • If being able to make the groups easily is enough information, then that is already a common duplicate: please refer to [How do I use itertools.groupby()?](https://stackoverflow.com/questions/773/) or [Group list by values](https://stackoverflow.com/questions/5695208). – Karl Knechtel Jan 02 '23 at 18:55

2 Answers2

1

You can use itertools.groupby.

from itertools import groupby

lst = [6, 1, 1, 1, 5, 1, 7, 1, 7, 1, 7, 7, 7, 1, 7, 1, 1, 3, 1, 1, 1, 1]

res = []
for k,g in groupby(lst):
    if k==1:
        res.append(len(list(g))+1)
    else:
        res.extend([1]*len(list(g)))

print(res)

Output:

[1, 4, 1, 2, 1, 2, 1, 2, 1, 1, 1, 2, 1, 3, 1, 5]
I'mahdi
  • 23,382
  • 5
  • 22
  • 30
1

Using itertools.groupby:

>>> from itertools import groupby
>>> x = [6, 1, 1, 1, 5, 1, 7, 1, 7, 1, 7, 7, 7, 1, 7, 1, 1, 3, 1, 1, 1, 1]
>>> new_x = []
>>> for i,g in groupby(x):
        if i==1:
            new_x.append(1+sum(g))
        else:
            new_x += [1 for _ in g]

        
>>> new_x
[1, 4, 1, 2, 1, 2, 1, 2, 1, 1, 1, 2, 1, 3, 1, 5]
mshsayem
  • 17,557
  • 11
  • 61
  • 69