0

data looks like this:

data=["q11-23-45","q11-23-46","q11-23-47","b11-73-50","q12-93-55","p11-23-59","p11-23-60","p11-23-61"]

trying to get something like:

q11-23-45 to 47

b11-73-50

q12-93-55

p11-23-59 to 61

tried

a=[]
b=[]
for i in range(0,len(data)):
    try:
        if int(data[i][-2:])+1!= int(data[i+1][-2:]):
            a.append(data[i])
        else:
            b.append(data[i])
    except:
        print(" out of index ")

tried to find solution but the given solutions like Identify groups of continuous numbers in a list

it's for integers in list and not strings + integers

Thank you in advance :)

Harsha Biyani
  • 7,049
  • 9
  • 37
  • 61
amin sama
  • 105
  • 1
  • 8

2 Answers2

1

You can try something like:

def convert(data, split_str):
    output = []
    for d_index, d in enumerate(data):
        d = str(d)
        if d_index == 0:
            same_start = [d]
            continue
        start = d.split(split_str)[0]
        last_start = data[d_index-1].split(split_str)[0]
        if start == last_start:
            same_start.append(d)
        else:
            same_start = [d]
        if same_start not in output:
            output.append(same_start)

    for single_output in output:
        if len(single_output) == 1:
            print(single_output[0])
        else:
            print(single_output[0] + " to " + str(single_output[-1]).split(split_str)[-1])


data= ["015 443 02 58",'015 443 02 59']
convert(data, " ")

print("=======")
data=["q11-23-45","q11-23-46","q11-23-47","b11-73-50","q12-93-55","p11-23-59","p11-23-60","p11-23-61"]
convert(data, "-")

Output:

015 443 02 58 to 59
=======    
q11-23-45 to 47
b11-73-50
q12-93-55
p11-23-59 to 61
Harsha Biyani
  • 7,049
  • 9
  • 37
  • 61
0

You can use defaultdict with max and min functions to achieve the desired output

from collections import defaultdict

data=["q11-23-45","q11-23-46","q11-23-47","b11-73-50","q12-93-55","p11-23-59","p11-23-60","p11-23-61"]

result = defaultdict(list)
for i in data:
    result[i[:i.rfind("-")]].append(i[i.rfind("-")+1:])

print(*[f"{i}-{min(result[i])} to {max(result[i])}" if max(result[i]) != min(result[i]) else f"{i}-{min(result[i])}" for i in result.keys()], sep="\n")

Output

q11-23-45 to 47
b11-73-50
q12-93-55
p11-23-59 to 61

This code will aggregate all items that have the same text until the last - the number that is coming after will be appended to the list of the dictionary item. Then the print statement is printing all the dictionary keys with the min and max values if they are not the same else it will print just one part.

Leo Arad
  • 4,452
  • 2
  • 6
  • 17