Sujet : Re: in Python? -- Chunk -- (ChunkC '(a a b b b)), ==> ((a 2) (b 3))
De : rob.cliffe (at) *nospam* btinternet.com (Rob Cliffe)
Groupes : comp.lang.pythonDate : 10. Jun 2024, 15:29:08
Autres entêtes
Message-ID : <mailman.109.1718115170.2909.python-list@python.org>
References : 1 2
User-Agent : Mozilla Thunderbird
import itertools
def chunk1(seq):
return [ ch * len(list(grp)) for (ch, grp) in itertools.groupby(s) ]
def chunk2(seq):
return [ (ch, len(list(grp))) for (ch, grp) in itertools.groupby(s) ]
s='aaabbccccaa'
print(chunk1(s))
print(chunk2(s))
###################################
Program output:
['aaa', 'bb', 'cccc', 'aa']
[('a', 3), ('b', 2), ('c', 4), ('a', 2)]
Rob Cliffe
On 09/06/2024 22:20, HenHanna via Python-list wrote:
>
Chunk, ChunkC -- nice simple way(s) to write these in Python?
>
>
(Chunk '(a a b a a a b b))
==> ((a a) (b) (a a a) (b b))
>
>
(Chunk '(a a a a b c c a a d e e e e))
==> ((a a a a) (b) (c c) (a a) (d) (e e e e))
>
>
(Chunk '(2 2 foo bar bar j j j k baz baz))
==> ((2 2) (foo) (bar bar) (j j j) (k) (baz baz))
>
_________________
>
(ChunkC '(a a b b b))
==> ((a 2) (b 3))
>
(ChunkC '(a a b a a a b b))
==> ((a 2) (b 1) (a 3) (b 2))