Home >Backend Development >PHP Tutorial >How to elegantly implement such a requirement for an array?

How to elegantly implement such a requirement for an array?

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-08-18 09:16:231020browse

There is an array[1,2,3,7,9,10,11,16]

Please tell me how to get it quickly and elegantly.1-3,7,9-11,16

What is the result like this?

I think this is to sort the array first and then loop to determine whether the current value is +1 from the previous one. Then splice strings based on the results. But it feels very cumbersome. I don’t know if there is any good and elegant way?

Thank you.

Reply content:

There is an array[1,2,3,7,9,10,11,16]

Please tell me how to get it quickly and elegantly.1-3,7,9-11,16

What is the result like this?

I think this is to sort the array first and then loop to determine whether the current value is +1 from the previous one. Then splice strings based on the results. But it feels very cumbersome. I don’t know if there is any good and elegant way?

Thank you.

This is the Python version (sorry, I don’t know PHP):

<code class="python">import itertools

def group_by_range(lst):
    lst.sort()
    for key, group in itertools.groupby(enumerate(lst), lambda t: t[1]-t[0]):
        rp = list(group)
        head, tail = rp[0][1], rp[-1][1]
        yield '{}-{}'.format(head, tail) if head!=tail else str(head)


if __name__ == '__main__':
    lst = [1,11,10,9,2,3,7,16]
    print(','.join(list(group_by_range(lst))))</code>

Questions I answered: Python-QA

My first thought was the same as the questioner=. =

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn