python平分列表和
时间: 2024-09-15 22:01:35 浏览: 57
在Python中,如果你想平分一个列表(即分割成两个长度相等的新列表),可以使用切片操作或者内置函数。以下是两种常见方法:
1. 切片操作:
```python
def split_list(input_list, n):
if len(input_list) % n != 0:
raise ValueError("List cannot be evenly divided.")
part_size = len(input_list) // n
return [input_list[i:i+part_size] for i in range(0, len(input_list), part_size)]
# 示例
original_list = [1, 2, 3, 4, 5, 6]
half_list = split_list(original_list, 2)
print(half_list) # 输出: [[1, 2], [3, 4], [5, 6]]
```
2. 使用内置函数 `zip` 和 list comprehension:
```python
def split_evenly(input_list, n):
if not isinstance(n, int) or n <= 0:
raise ValueError("n must be a positive integer.")
return [list(group) for group in zip(*[iter(input_list)] * n)]
# 示例
original_list = [1, 2, 3, 4, 5, 6]
half_list = split_evenly(original_list, 2)
print(half_list)
阅读全文