2

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?

1

3 Answers 3

3

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]
Sign up to request clarification or add additional context in comments.

2 Comments

thanks, i made a modification to the return using the chain from itertools return list(chain(range(int(begin), int(end) + 1)))
Sorry, I forgot the range. I don't think you need chain.
0
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],
]

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.