Charles
Charles

Reputation: 23

Convert array range given as string to numbers

I have the following arrays from a scraped STAAD Pro. input file.

I want to replace the TO by the actual range.

Example array items:

[["638TO640"], ["3033", "3038", "4081", "4087"], ["601TO615", "617"]]

what I would like these array items to become:

[[638, 639, 640], [3033, 3038, 4081, 4087], [601, 602, 603, 604,... 615, 617]]

Is there a simple pythonic way of achieving the conversion?

Upvotes: 2

Views: 117

Answers (3)

mkrieger1
mkrieger1

Reputation: 23150

Simply parse the two numbers from the string by using a regular expression and create a range object:

import re

def str_to_range(s):
    begin, end = re.match(r'(\d+)TO(\d+)', s).groups()
    return list(range(int(begin), int(end) + 1))
>>> str_to_range('638TO640')
[638, 639, 640]

Upvotes: 3

v0rtex20k
v0rtex20k

Reputation: 1121

All you need is some simple string processing:

from typing import List
from itertools import chain

def range_to_numbers(staad_list: List[List[str]])-> List[List[int]]:
    new_list = []
    for slist in staad_list:
        for i in range(len(slist)):
            if slist[i].isnumeric(): slist[i] = [int(slist[i])]
            elif 'to' in slist[i].strip().lower():
                try:
                    to_idx = slist[i].lower().find('to')
                    start, end = int(slist[i][:to_idx]), int(slist[i][to_idx+2:])
                    slist[i] = [i for i in range(start, end)]
                except ValueError: print('Invalid key'); exit()
        new_list.append(list(chain(*slist)))
    return new_list

# run it with range_to_numbers(your_array)

Upvotes: 0

Vishal Singh
Vishal Singh

Reputation: 6234

mylist = [
    ["638TO640"],
    ["638TO6400"],
    ["3033", "3038", "4081", "4087"],
    ["601TO615", "617"],
]


def expand_range(str_numbers):
    numbers = []
    for num in str_numbers:
        try:
            numbers.append(int(num))
        except ValueError:
            start, end = num.split("TO")
            numbers.extend(range(int(start), int(end) + 1))

    return numbers


new_list = [expand_range(sublist) for sublist in mylist]

Output:

[
    [638, 639, 640],
    [3033, 3038, 4081, 4087],
    [601, 602, 603, 604, 605, 606, 607, 608, 609, 610, 611, 612, 613, 614, 615, 617],
]

Upvotes: 0

Related Questions