# 將 Python 列表一分為二

Hemank Mehtani 2023年1月30日

## 在 Python 中使用列表切片將列表分成兩半

``````lst = ["a", "b", "c", "d", "e", "f"]
print(lst[:3])
print(lst[3:])
``````

``````['a', 'b', 'c']
['d', 'e', 'f']
``````

``````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']
``````

## Python 中使用 `islice()` 函式將列表拆分為一半

``````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']]
``````