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

如何将Python一维列表转换为相邻元素成对的嵌套列表?

How to Convert a Flat List to a List of Consecutive Element Pairs

Got it, let's break down how to solve this problem. You want to take a list like [a, b, c, d] and turn it into [[a,b], [b,c], [c,d]]—essentially creating consecutive pairs of elements from the original list. Here are a few clean, efficient ways to do this in Python, even for large lists with thousands of elements:

Method 1: List Comprehension with Slicing

This is a straightforward, readable approach. We iterate through the list up to the second-last element, and for each index i, we take a slice of the list from i to i+2 (which gives us the pair of elements at positions i and i+1):

A = [1, 2, 3, 4]
desired_A = [A[i:i+2] for i in range(len(A) - 1)]
print(desired_A)  # Output: [[1,2], [2,3], [3,4]]

Why this works:

  • range(len(A) - 1) generates indices from 0 to len(A)-2 (since we don't want to go beyond the second-last element—there's no element after the last one to pair with).
  • A[i:i+2] creates a sublist containing the elements at positions i and i+1. For large lists, slicing is efficient in Python, so this handles thousands of elements without issues.

Method 2: Using zip()

This is a more concise, Pythonic approach. zip(A, A[1:]) pairs each element in A with the next element (since A[1:] is the original list shifted by one position). We then convert each tuple from zip() into a list:

A = [1, 2, 3, 4]
desired_A = [list(pair) for pair in zip(A, A[1:])]
print(desired_A)  # Output: [[1,2], [2,3], [3,4]]

Why this works:

  • zip(A, A[1:]) iterates over both lists in parallel, producing tuples like (1,2), (2,3), etc.
  • Converting each tuple to a list gives us the nested list structure we want. zip() is implemented in C, so it's very fast even for large datasets—great for your thousand-element list.

Edge Cases to Consider

  • If the input list has 0 or 1 elements, both methods will return an empty list (since you can't form any pairs). For example:
    A = [5]
    desired_A = [A[i:i+2] for i in range(len(A)-1)]  # Output: []
    
  • For very large lists where you don't need to store the entire nested list in memory (e.g., just iterating over pairs), you can use a generator expression instead of a list comprehension:
    pair_generator = (A[i:i+2] for i in range(len(A)-1))
    # Or using zip:
    pair_generator = (list(pair) for pair in zip(A, A[1:]))
    
    This saves memory because it generates pairs one at a time instead of creating the entire list upfront.

Both methods are efficient and easy to read—pick whichever you find more intuitive!

内容的提问来源于stack exchange,提问作者Abhijeet Bhati

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:54:45