List集合判断集合内元素是否有交叉111222333这样算没有交叉112122333这样算有交叉取出交叉的部分
要判断集合内元素是否有交叉,可以先将集合转化为列表,然后遍历列表,检查是否存在相邻元素相等的情况。如果存在相邻元素相等,则说明集合内元素有交叉。
以下是判断集合内元素是否有交叉的Python代码:
def has_intersection(lst):
for i in range(1, len(lst)):
if lst[i] == lst[i-1]:
return True
return False
# 示例测试
lst1 = [1, 1, 1, 2, 2, 2, 3, 3, 3]
lst2 = [1, 1, 2, 1, 2, 2, 3, 3, 3]
print(has_intersection(lst1)) # 输出 False
print(has_intersection(lst2)) # 输出 True
如果要取出交叉的部分,可以使用两个指针(start和end)来记录交叉部分的起始和结束位置,然后通过切片操作获取交叉部分的元素。
以下是取出交叉部分的Python代码:
def get_intersection(lst):
start = None
end = None
for i in range(1, len(lst)):
if lst[i] == lst[i-1]:
if start is None:
start = i-1
end = i
if start is not None and end is not None:
return lst[start:end+1]
else:
return []
# 示例测试
lst1 = [1, 1, 1, 2, 2, 2, 3, 3, 3]
lst2 = [1, 1, 2, 1, 2, 2, 3, 3, 3]
print(get_intersection(lst1)) # 输出 []
print(get_intersection(lst2)) # 输出 [1, 2, 2]
注意:以上代码假设交叉部分是连续的。如果交叉部分可以是不连续的,则需要稍作修改
原文地址: https://www.cveoy.top/t/topic/ihb7 著作权归作者所有。请勿转载和采集!