gpt4 book ai didi

python - 如果值为空,则拆分字典列表?

转载 作者:太空宇宙 更新时间:2023-11-04 10:09:55 25 4
gpt4 key购买 nike

我想拆分字典列表如果值为空并创建新的列表列表。

输入:

[{'k':'a'},{'k':'b'},{'k':''},{'k':'d'},{'k':''},{'k':'f'},{'k':'g'}]

输出:

[[{'k': 'a'}, {'k': 'b'}, {'k': ''}], [{'k': 'd'}, {'k': ''}], [{'k': 'f'}, {'k': 'g'}]]

我试过使用循环,如果它工作正常。

sub_header_list = [{'k':'a'},{'k':'b'},{'k':''},{'k':'d'},{'k':''},{'k':'f'},{'k':'g'}]
index_data = [] ; data_list = []
for i in sub_header_list:
index_data.append(i)
if i['k'] == '':
data_list.append(index_data)
index_data = []
print(data_list+[index_data])

[[{'k': 'a'}, {'k': 'b'}, {'k': ''}], [{'k': 'd'}, {'k': ''}], [{'k': 'f'}, {'k': 'g'}]]

是否有任何 pythonic 方法可以实现相同的目的,我的意思是通过使用内置函数或其他方法?

最佳答案

这是另一种 Pythonic 的实现方式:

>>> d = [{'k':'a'}, {'k':'b'}, {'k':''}, {'k':'d'}, {'k':''}, {'k':'f'}, {'k':'g'}]
>>> index_list = [i + 1 for i, x in enumerate(d) if x == {'k': ''}]
>>> [d[i:j] for i, j in zip([0] + index_list, index_list + [len(d)])]
[[{'k': 'a'}, {'k': 'b'}, {'k': ''}], [{'k': 'd'}, {'k': ''}], [{'k': 'f'}, {'k': 'g'}]]

关于python - 如果值为空,则拆分字典列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38994257/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com