Last active
August 20, 2020 09:33
-
-
Save shinwachi/e7b8abfda38553fdb752c719a9ddee0d to your computer and use it in GitHub Desktop.
chunked range in python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ''' | |
| with runt [(0, 2000), (2000, 4000), (4000, 6000), (6000, 7000)] | |
| no runt [(0, 2000), (2000, 4000), (4000, 6000)] | |
| [{'x': (0, 2000), 'y': (0, 2100), 'idx_xy': (0, 0)}, | |
| {'x': (2000, 4000), 'y': (0, 2100), 'idx_xy': (1, 0)}, | |
| {'x': (4000, 6000), 'y': (0, 2100), 'idx_xy': (2, 0)}, | |
| {'x': (0, 2000), 'y': (2100, 4200), 'idx_xy': (0, 1)}, | |
| {'x': (2000, 4000), 'y': (2100, 4200), 'idx_xy': (1, 1)}, | |
| {'x': (4000, 6000), 'y': (2100, 4200), 'idx_xy': (2, 1)}, | |
| {'x': (0, 2000), 'y': (4200, 6300), 'idx_xy': (0, 2)}, | |
| {'x': (2000, 4000), 'y': (4200, 6300), 'idx_xy': (1, 2)}, | |
| {'x': (4000, 6000), 'y': (4200, 6300), 'idx_xy': (2, 2)}] | |
| ''' | |
| def chunk_range(length, chunk_size, runt=False): | |
| # chunk points: [0, 1000, 2000, ...] | |
| chunk_points = list(range(0,length,chunk_size)) | |
| # chunk ranges: [(0, 1000), (1000, 2000), .... (6000, 6500)] <<< last one is "runt" | |
| chunk_ranges = list(zip(chunk_points, chunk_points[1:]+[width])) | |
| if runt==True: | |
| return chunk_ranges | |
| else: | |
| # cut off runt | |
| return [p for p in chunk_ranges if p[1]-p[0] == chunk_size] | |
| print("with runt", chunk_range(7000, 2000, True)) | |
| print("no runt", chunk_range(7000, 2000, False)) | |
| def chunk_rect(len_x, len_y, chunk_x, chunk_y, runt=False): | |
| chunk_range_x = chunk_range(len_x, chunk_x, runt) | |
| chunk_range_y = chunk_range(len_y, chunk_y, runt) | |
| nested_list = [[ dict(x=x,y=y, idx_xy=(idx_x,idx_y)) for idx_x, x in enumerate(chunk_range_x)] for idx_y, y in enumerate(chunk_range_y)] | |
| return nested_list | |
| def flatten_nested_list(nested_list): | |
| # https://stackoverflow.com/questions/11264684/flatten-list-of-lists/11264799 | |
| flattened = [val for sublist in nested_list for val in sublist] | |
| return flattened | |
| flatten_nested_list(chunk_rect(7500, 7000, 2000, 2100, False)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment