数据如下所示:
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 ")
试图找到解决方案,但给定的解决方案,如识别列表中的连续数字组
它适用于列表中的整数,而不是字符串+整数
提前感谢:(
您可以尝试以下操作:
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
您可以使用带有max和min函数的defaultdict来实现所需的输出
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")
输出
q11-23-45 to 47
b11-73-50
q12-93-55
p11-23-59 to 61
此代码将聚合所有具有相同文本的项,直到最后一个-
(后面的数字将附加到字典项的列表中(。然后print语句将打印具有最小值和最大值的所有字典键,如果它们不相同,则只打印一部分。