这是一个在Python中展平一个浅列表的例子。
首先,我们定义一个函数`flatten`,它接受一个列表作为参数。在这个函数中,我们将使用列表推导式来遍历输入列表中的每个元素。如果当前元素是列表,我们就递归地调用`flatten`函数;如果不是列表,我们就将其添加到结果列表中。
```python
def flatten(lst):
return [item for sublist in lst for item in (sublist if isinstance(sublist, list) else [sublist])]
```
然后,我们定义一个测试用例来验证我们的函数是否正确工作。
```python
def test_flatten():
assert flatten([1, 2, [3, 4], [5, [6, 7]]]) == [1, 2, 3, 4, 5, 6, 7]
assert flatten([[1, 2, [3, 4]], 5]) == [1, 2, 3, 4, 5]
print("All test cases passed.")
test_flatten()
```
最后,我们使用这个函数来展平一个列表。
```python
flat_list = flatten([1, 2, [3, 4], [5, [6, 7]]])
print(flat_list) # Output: [1, 2, 3, 4, 5, 6, 7]
```
这个函数可以通过递归的方式来展平列表,如果遇到嵌套的列表,就继续展开。这种方法简单且易于理解,但是需要注意的是,对于非常大的列表或者深层次嵌套的列表,这种方式可能会导致栈溢出。