我有这个列表
list_dict = [
{'id': 1},
{'item': 'apple'},
{'id': 2},
{'item': 'pear'},
{'id': 1},
{'item': 'peach'},
{'id': 2},
{'item': 'kiwi'},
{'id': 3},
{'item': 'banana'},
{'id': 4},
{'item': 'mango'},
{'id': 1},
{'item': 'watermelon'},
{'id': 2},
{'item': 'plum'},
{'id': 3},
{'item': 'grapes'}]
和我想分割成这样(当"id"1)
result = [
[{'id': 1},
{'item': 'apple'},
{'id': 2},
{'item': 'pear'}],
[{'id': 1},
{'item': 'peach'},
{'id': 2},
{'item': 'kiwi'},
{'id': 3},
{'item': 'banana'},
{'id': 4},
{'item': 'mango'}],
[{'id': 1},
{'item': 'watermelon'},
{'id': 2},
{'item': 'plum'},
{'id': 3},
{'item': 'grapes'}]]
可以使用嵌套的for循环
list_dict = [{"id":1},{"item":"apple"},{"id":2},{"item":"pear"},{"id":1},{"item":"peach"},{"id":2},{"item":"kiwi"},{"id":3},{"item":"banana"},{"id":4},{"item":"mango"},{"id":1},{"item":"watermelon"},{"id":2},{"item":"plum"},{"id":3},{"item":"grapes"}]
output = []
temp = []
for i in list_dict:
if i.get('id', -1) == 1 and temp:
output.append(temp.copy())
temp.clear()
temp.append(i)
else:
temp.append(i)
output.append(temp.copy())
print(output)
#[[{'id': 1}, {'item': 'apple'}, {'id': 2}, {'item': 'pear'}], [{'id': 1}, {'item': 'peach'}, {'id': 2}, {'item': 'kiwi'}, {'id': 3}, {'item': 'banana'}, {'id': 4}, {'item': 'mango'}], [{'id': 1}, {'item': 'watermelon'}, {'id': 2}, {'item': 'plum'}, {'id': 3}, {'item': 'grapes'}]]
也许是这样的?
main_list = []
current_list = []
for el in list_dict:
if el.get("id", 0) == 1:
if current_list:
main_list.append(current_list)
current_list = [el]
else:
current_list.append(el)
if current_list:
main_list.append(current_list)
print(main_list)