You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中提取列表连续重复块的首尾元素生成新列表?

Hey there! Let's figure out how to solve this problem where we need to extract the first and last elements of each consecutive duplicate block in a list and build a new list from those. Here are two straightforward approaches in Python:

方法1:手动遍历(基础实现)

This approach uses a simple loop to track each consecutive block. We'll keep an eye on the start of the current block and its value, then add the first and last elements of the block to our new list whenever we hit a different value.

a = [1,1,1,1,0,0,0,1,1,0,0,0,1,1,1]
new_list = []

# Handle empty list case to avoid index errors
if not a:
    print(new_list)
else:
    current_value = a[0]
    start_index = 0
    # Iterate through the list starting from the second element
    for i in range(1, len(a)):
        if a[i] != current_value:
            # Add first and last element of the current block
            new_list.append(a[start_index])
            new_list.append(a[i-1])
            # Update tracking variables for the next block
            current_value = a[i]
            start_index = i
    # Don't forget to add the last block's elements
    new_list.append(a[start_index])
    new_list.append(a[-1])

print(new_list)  # Output: [1, 1, 0, 0, 1, 1, 0, 0, 1, 1]

逻辑说明:

  • We first check if the input list is empty to prevent index-related errors.
  • We track the value of the current consecutive block and its starting index.
  • When we encounter a new value, we append the first (a[start_index]) and last (a[i-1]) elements of the current block to new_list.
  • After the loop ends, we add the elements of the final block (since there's no new value to trigger the append inside the loop).
方法2:使用itertools.groupby(简洁实现)

Python's standard library has itertools.groupby, which is perfect for grouping consecutive duplicate elements. This approach is more concise and leverages built-in functionality.

from itertools import groupby

a = [1,1,1,1,0,0,0,1,1,0,0,0,1,1,1]
new_list = []

# Group consecutive elements and process each group
for key, group in groupby(a):
    group_elements = list(group)
    # Append first and last element of the group
    new_list.append(group_elements[0])
    new_list.append(group_elements[-1])

print(new_list)  # Output: [1, 1, 0, 0, 1, 1, 0, 0, 1, 1]

逻辑说明:

  • groupby(a) iterates through the list and groups consecutive elements with the same value. Each iteration gives us a key (the value of the group) and a group (an iterator over the elements in the group).
  • We convert the group iterator to a list, then take its first and last elements to add to new_list.
  • This method is shorter and easier to read once you're familiar with groupby.

内容的提问来源于stack exchange,提问作者Charanya G

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:37:33