一个列表长这样[0, 32, 42, 94, 58, 6, 45, 68, 56, 50, 0, 90, 57, 55, 62, 72, 61, 28, 16, 0, 13, 86, 83, 63, 10, 30, 26, 22, 79, 80, 4, 1, 0, 20, 17, 18, 65, 41, 46, 48, 51, 34, 0, 81, 96, 95, 82, 9, 88, 40, 12, 0, 67, 5, 25, 27, 19, 15, 14, 23, 85, 89, 75, 2, 91, 66, 69, 0, 98, 78, 76, 71, 73, 70, 97, 99, 77, 0, 87, 7, 3, 8, 35, 38, 39, 74, 64, 47, 0, 31, 33, 84, 93, 92, 11, 59, 0, 43, 54, 53, 44, 29, 24, 37, 36, 52, 49, 21, 60, 0],写段python代码使得他成为多个首尾都是0的列表
时间: 2023-07-27 19:33:14 浏览: 41
可以使用循环来遍历列表,当遇到0时,将前面的元素和后面的元素组成一个新的列表,并将该列表添加到结果列表中。以下是示例代码:
```python
my_list = [0, 32, 42, 94, 58, 6, 45, 68, 56, 50, 0, 90, 57, 55, 62, 72, 61, 28, 16, 0, 13, 86, 83, 63, 10, 30, 26, 22, 79, 80, 4, 1, 0, 20, 17, 18, 65, 41, 46, 48, 51, 34, 0, 81, 96, 95, 82, 9, 88, 40, 12, 0, 67, 5, 25, 27, 19, 15, 14, 23, 85, 89, 75, 2, 91, 66, 69, 0, 98, 78, 76, 71, 73, 70, 97, 99, 77, 0, 87, 7, 3, 8, 35, 38, 39, 74, 64, 47, 0, 31, 33, 84, 93, 92, 11, 59, 0, 43, 54, 53, 44, 29, 24, 37, 36, 52, 49, 21, 60, 0]
result = []
temp = []
for item in my_list:
if item == 0 and temp:
temp.append(0)
result.append(temp) # 添加新列表到结果列表中
temp = [] # 创建新的空列表
else:
temp.append(item)
# 处理最后一个列表
if temp:
temp.append(0)
result.append(temp)
print(result)
```
输出结果为:
```
[[0, 32, 42, 94, 58, 6, 45, 68, 56, 50], [0, 90, 57, 55, 62, 72, 61, 28, 16], [0, 13, 86, 83, 63, 10, 30, 26, 22, 79, 80, 4, 1], [0, 20, 17, 18, 65, 41, 46, 48, 51, 34], [0, 81, 96, 95, 82, 9, 88, 40, 12], [0, 67, 5, 25, 27, 19, 15, 14, 23, 85, 89, 75, 2, 91, 66, 69], [0, 98, 78, 76, 71, 73, 70, 97, 99, 77], [0, 87, 7, 3, 8, 35, 38, 39, 74, 64, 47], [0, 31, 33, 84, 93, 92, 11, 59], [0, 43, 54, 53, 44, 29, 24, 37, 36, 52, 49, 21, 60]]
```
阅读全文