Python 从数据帧/列表中识别结束连续编号的组
数据如下所示:Python 从数据帧/列表中识别结束连续编号的组,python,list,range,continuous,Python,List,Range,Continuous,数据如下所示: 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
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
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, "-")
尝试
试图找到解决方案,但给出的解决方案如下
它用于列表中的整数,而不是字符串+整数
提前感谢:)您可以尝试以下方法:
q11-23-45 to 47
b11-73-50
q12-93-55
p11-23-59 to 61
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
您可以将defaultdict与max和min函数一起使用,以实现所需的输出
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语句将使用最小值和最大值打印所有字典键,如果它们不相同,则只打印一部分。small怀疑@Harsh Biyani如果列表中有数字,它将无法正常工作?示例['015 443 02 58','015 443 02 59']@aminsama您可以将其转换为字符串then@aminsama:我修改了答案非常感谢!但是我们可以比较最后两个字符而不是找到一个-或““@aminsama:是的,我们可以。您可以删除所有字母数字字符,并可以找到
split\u str
非常感谢!但是我们能比较最后两个字符而不是找到一个“-”