简体   繁体   中英

more efficient use of itertools.groupby()

I am trying to enhance my knowledge of the itertools library, since it's so generally useful. To that end, I'm trying to solve an interview puzzler I came across. A large portion of it involves sequentially counting the number of grouped and repeated digits within a number. For example, for the number:

1223444556

I want:

[(1,1),(2,2),(1,3),(3,4),(2,5),(1,6)]

which is to say, from left to right, there is 1 one, 2 twos, 1 three, and so forth.

Here is my current code:

from itertools import groupby
groups_first = [int(''.join(v)[0]) for k,v in groupby(str(1223444556))]
counts = [len(''.join(v)) for k,v in groupby(str(1223444556))]
zip(counts,groups_first)

It works, but what I would like to know is whether there is a more compact way of doing this that bypasses zipping two lists together. Any thoughts? I think this may go to doing some sort of lambda function in groupby(), but I can't see it yet.

Thanks!

I'd probably just write

>>> n = 1223444556
>>> [(len(list(g)), int(k)) for k,g in groupby(str(n))]
[(1, 1), (2, 2), (1, 3), (3, 4), (2, 5), (1, 6)]

怎么样:

[(sum(1 for _ in v), int(k)) for k,v in groupby(str(1223444556))]

I'd probably opt for collections instead:

>>> from collections import Counter
>>> c = Counter('1223444556')
>>> c.items()
[('1', 1), ('3', 1), ('2', 2), ('5', 2), ('4', 3), ('6', 1)]

if the order is important (as you say in your comment), this may no longer be the most efficient method. But for full consideration, you could do this:

>>> t = c.items()
>>> t = sorted(t)

And if you want y, x to be listed as x, y, you could then do this:

>>> t = [(y, x) for x, y in t]
>>> print t
[(1, '1'), (2, '2'), (1, '3'), (3, '4'), (2, '5'), (1, '6')]

One value of this method is that the repeated element is listed as a string, so there is no confusion about which number comes from the original list and which number indicates frequency.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM