Select to view content in your preferred language

Calculating Ranges of Non-Consecutive List

685
2
Jump to solution
10-27-2022 09:27 AM
MAmbrosini
Emerging Contributor

I have a script that needs to calculate the location numbers within a page and provide the ranges in a formatted list that will be used to fill out a text field to be used with dynamic text. There are often locations missing, so the list won't be consecutive. Right now I have the code below which accomplishes that, but if there is a single non consecutive location it lists it as a range itself i.e. 5-5. Is there a way to edit the script to prevent this?

loc_numbers = [row[0] for row in arcpy.da.SearchCursor(join_lyr, "Map_ID")]


ranges = sum((list(t) for t in zip(loc_numbers, loc_numbers[1:]) if t[0]+1 != t[1]), [])
iranges = iter(loc_numbers[0:1] + ranges + loc_numbers[-1:])
range_values = ', '.join([str(n) + '-' + str(next(iranges)) for n in iranges])

Tags (4)
0 Kudos
1 Solution

Accepted Solutions
DonMorrison1
Frequent Contributor

Here is a very inelegant way to do it - add this after your code

fixed_range_values = ', '.join([r if r.split('-')[0] != r.split('-')[1] else r.split('-')[0] for r in range_values.replace(' ','').split(',')])

 

View solution in original post

2 Replies
DonMorrison1
Frequent Contributor

Here is a very inelegant way to do it - add this after your code

fixed_range_values = ', '.join([r if r.split('-')[0] != r.split('-')[1] else r.split('-')[0] for r in range_values.replace(' ','').split(',')])

 

MAmbrosini
Emerging Contributor

That worked, thank you!

0 Kudos