Home > OS >  How to turn a text file with number ranges into a list variable?
How to turn a text file with number ranges into a list variable?

Time:11-10

I have a text file with:

8-9, 12, 14-16, 19, 27-28, 33, 41, 43, 45-46, 48-49, 51,54-60, 62-74, 76-82, 84-100, 102-105, 107-108

It is basically a list of integers in a text file. Using Python, I want to turn this into a list where every variable is stored separately. But the problem is that the dashes between the numbers represents a range, implying that 62-74 is actually 62,63,64,65,66,67,68,69,70,71,72,73,74.

So my program should be able to read the text and if it encounters any dash it should append the list with the numbers within that range.

Do you have any idea how to do that?

I tried to create a list with integers in a text file.

CodePudding user response:

Try this:

num_list = ["8-9", "12", "14-16", "19", "27-28", "33", "41", "43", "45-46", "48-49", "51","54-60", "62-74", "76-82", "84-100", "102-105", "107-108"]
output_list = []

for number in num_list:
    if "-" in number: # Checks if the string contains "-"
        num1, num2 = number.split(sep="-") # Splits the numbers
        num1 = int(num1) # Setting the number from string to integer
        num2 = int(num2) # Setting the number from string to integer
        while num1 <= num2:
            output_list.append(num1) # append to output list
            num1  = 1
    else:
        output_list.append(int(number)) # append to output list

print(output_list)

Output:

[8, 9, 12, 14, 15, 16, 19, 27, 28, 33, 41, 43, 45, 46, 48, 49, 51, 54, 55, 56, 57, 58, 59, 60, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 76, 77, 78, 79, 80, 81, 82, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 102, 103, 104, 105, 107, 108]

CodePudding user response:

You just want to check if there is a "-" in the string. If it's there, use the built-in range function to generate the list. This might work for you.

vals = [
    "8-9", "12", "14-16", 
    "19", "27-28", "33", 
    "41", "43", "45-46", 
    "48-49", "51", "54-60", 
    "62-74", "76-82", "84-100", 
    "102-105", "107-108"
]

output = []
for val in vals:
    if "-" not in val:
        output.append(int(val))
    else:
        bounds = val.split("-")
        output  = [i for i in range(int(bounds[0]), int(bounds[1]) 1)]

print(output)
# >>> [8, 9, 12, 14, 15, 16, 19, 27, 28, 33, 41, 43, 45, 46, 48, 49, 51, 54, 55, 56, 57, 58, 59, 60, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 76, 77, 78, 79, 80, 81, 82, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 102, 103, 104, 105, 107, 108]
  • Related