将 Python 列表一分为二
    
    
            Hemank Mehtani
    2023年1月30日
    
    Python
    Python list
    
 
列表在特定索引处存储元素并且是可变的,这意味着我们可以稍后更新列表中的值。
我们将在本教程中学习如何将列表分成两半。
在 Python 中使用列表切片将列表分成两半
列表切片抓取列表的特定部分进行某些操作,而原始列表不受影响。这意味着它会创建列表的副本来执行分配的任务。Python 中的切片运算符 ([:] ) 用于此目的。
我们在以下代码中将列表分成两半。
lst = ["a", "b", "c", "d", "e", "f"]
print(lst[:3])
print(lst[3:])
输出:
['a', 'b', 'c']
['d', 'e', 'f']
我们还可以创建一个函数将列表分成两半。我们将使用 len() 函数来查找列表的长度。我们将这个值减半并使用列表切片方法将它分成两半。
例如,
def split_list(a_list):
    half = len(a_list) // 2
    return a_list[:half], a_list[half:]
A = ["a", "b", "c", "d", "e", "f"]
B, C = split_list(A)
print(B)
print(C)
输出:
['a', 'b', 'c']
['d', 'e', 'f']
我们创建了一个函数 split_list,它返回现有列表的两半。
请注意,它不会更改原始列表,因为它会创建一个重复的列表来执行分配的任务。
Python 中使用 islice() 函数将列表拆分为一半
在 Python 中,itertools 是内置模块,允许我们有效地处理迭代器。
它使迭代列表和字符串等可迭代对象变得非常容易。islice 函数是 itertools 模块的一部分。它有选择地打印作为参数传递的可迭代容器中提到的值。
例如,
from itertools import islice
Input = ["a", "b", "c", "d", "e", "f"]
length_to_split = [len(Input) // 2] * 2
lst = iter(Input)
Output = [list(islice(lst, elem)) for elem in length_to_split]
print("Initial list:", Input)
print("After splitting", Output)
输出:
Initial list: ['a', 'b', 'c', 'd', 'e', 'f']
After splitting [['a', 'b', 'c'], ['d', 'e', 'f']]
在 Python 中使用 accumulate() 函数将列表分成两半
zip() 函数用于组合来自可迭代对象的元素。我们可以将它与 itertools 模块中的 accumulate() 函数一起使用,将列表分成两半。
例如,
from itertools import accumulate
Input = ["a", "b", "c", "d", "e", "f"]
length_to_split = [len(Input) // 2] * 2
Output = [
    Input[x - y : x] for x, y in zip(accumulate(length_to_split), length_to_split)
]
print("Initial list :", Input)
print("After splitting", Output)
输出:
Initial list : ['a', 'b', 'c', 'd', 'e', 'f']
After splitting [['a', 'b', 'c'], ['d', 'e', 'f']]
        Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe