首页 > 解决方案 > 从数据框/列表中识别结束连续数字组

问题描述

数据如下所示:

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"]

试图得到类似的东西:

q11-23-45 to 47

b11-73-50

q12-93-55

p11-23-59 to 61

试过了

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 ")

试图找到解决方案,但给定的解决方案,如识别列表中的连续数字组

它适用于列表中的整数,而不是字符串 + 整数

先感谢您 :)

标签: pythonlistrangecontinuous

解决方案


您可以尝试以下方法:

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, "-")

输出

015 443 02 58 to 59
=======    
q11-23-45 to 47
b11-73-50
q12-93-55
p11-23-59 to 61

推荐阅读