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
Release: 2016-08-18 09:16:23
Original
1029 people have browsed it

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):

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))))
Copy after login

Questions I answered: Python-QA

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

Related labels:
Statement of this Website
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
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template