python - 从数据框/列表中识别结束连续数字组
问题描述
数据如下所示:
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
推荐阅读
- c# - 如何通过安装文件使用 Visual Studio 安装 2017 进行升级
- c# - 如何将数据导入数据集并在 Google Cloud AutoML 中重新训练自定义模型
- .net - 您如何在 GraphQL 授权中记录安全性?
- firebase - 优化数据模型 Firestore
- sql - 将特定数据值拉入一行的最佳方法是什么?
- yii2 - 2 一个控制器中的删除功能 yii2
- reactjs - ESLint 必须使用解构状态赋值
- python - Compare dataframe cell value with series then find sum
- sql-server - 有人可以逐步指导我解决这个问题吗?对称对问题
- c# - 检索项目的父项时出错:找不到与给定名称“ThemeOverlay.AppCompat.Light”匹配的资源