一个列表长这样[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 18:33:14 浏览: 52
我就是这样学习Python中的列表
可以使用一个循环来遍历列表,当遇到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]
new_list = []
for item in my_list:
if item == 0:
print(new_list) # 打印新列表
new_list = [] # 创建新列表
else:
new_list.append(item) # 添加元素到新列表中
print(new_list) # 打印最后一个新列表
```
输出结果为:
```
[]
[32, 42, 94, 58, 6, 45, 68, 56, 50]
[90, 57, 55, 62, 72, 61, 28, 16]
[13, 86, 83, 63, 10, 30, 26, 22, 79, 80, 4, 1]
[20, 17, 18, 65, 41, 46, 48, 51, 34]
[81, 96, 95, 82, 9, 88, 40, 12]
[67, 5, 25, 27, 19, 15, 14, 23, 85, 89, 75, 2, 91, 66, 69]
[98, 78, 76, 71, 73, 70, 97, 99, 77]
[87, 7, 3, 8, 35, 38, 39, 74, 64, 47]
[31, 33, 84, 93, 92, 11, 59]
[43, 54, 53, 44, 29, 24, 37, 36, 52, 49, 21, 60]
[]
阅读全文