如何在列表首个元素重复时自动创建新列表?
列表按首个元素重复分割的实现方法
核心逻辑
每次从当前起始位置开始,以该位置的元素为标记,找到它后续第一次出现的位置,将起始位置到该标记位置的元素作为一个子列表,再从标记位置的下一位开始重复这个过程,直到遍历完整个列表。
方法一:利用列表内置index方法
def split_on_first_duplicate(lst): result = [] start = 0 while start < len(lst): current_first = lst[start] # 从start+1开始查找当前起始元素的下一个出现位置 try: end = lst.index(current_first, start + 1) except ValueError: # 若后续无重复元素,截取剩余全部元素 end = len(lst) - 1 # 截取子列表(包含end位置的元素) sub_list = lst[start:end+1] result.append(sub_list) start = end + 1 return result # 测试示例 list1 = [2, 3, 4, 5, 2, 1, 9, 4, 7, 8, 1] newlists = split_on_first_duplicate(list1) newlist1, newlist2 = newlists[0], newlists[1] print(newlist1) # 输出:[2, 3, 4, 5, 2] print(newlist2) # 输出:[1, 9, 4, 7, 8, 1]
方法二:手动遍历查找
如果不想用内置方法,可以手动遍历列表找到重复位置:
def split_on_first_duplicate(lst): result = [] start = 0 total_len = len(lst) while start < total_len: current_first = lst[start] end = start # 从start+1开始遍历找重复元素 for i in range(start + 1, total_len): if lst[i] == current_first: end = i break else: # 遍历完未找到重复,取到列表末尾 end = total_len - 1 sub_list = lst[start:end+1] result.append(sub_list) start = end + 1 return result # 测试示例 list1 = [2, 3, 4, 5, 2, 1, 9, 4, 7, 8, 1] newlists = split_on_first_duplicate(list1) newlist1, newlist2 = newlists[0], newlists[1] print(newlist1) # 输出:[2, 3, 4, 5, 2] print(newlist2) # 输出:[1, 9, 4, 7, 8, 1]
内容的提问来源于stack exchange,提问作者nsp077
相关产品推荐
相关产品推荐

