我想知道是否有一种Python式的方法来压缩这个嵌套的for循环:dict = { "keyA": { "subkey1": { "A1a": "frog", "A1b": "dog", "A1c": "airplane" } }, "keyA": { "subkey2": { "A2a": "cat" } }, "keyB": { "subkey1": { "B1a": "Zorba", "B1q": ["popcorn", -34] } }, "keyB": { "subkey2": { "B2z": "A Man A Plan A Canal", "B2e": "armadillo", "B2w": [1, 3, "jump"] } }, "keyC": { "subkey1": { "C1a": 3.14, "C1z": { "aaa": "dishwater", "bbb": "Dishwalla" }, "C1x": "bat" } }, "keyC": { "subkey2": { "C2a": None, "C2b": 123 } }}for key in dict.keys(): for subsubkey in dict[key]["subkey2"].keys(): print(key+":"+subsubkey)输出:keyA:A2akeyB:B2zkeyB:B2ekeyB:B2wkeyC:C2akeyC:C2b
1 回答
阿晨1998
TA贡献2037条经验 获得超6个赞
解决这个问题的一种 Pythonic 方法是使用列表理解。这允许您在一行中定义一个列表,遵循for
您已经布置的循环结构。工作版本可能类似于:
final_keys = [(first_key, second_key) for first_key in dict.keys() for second_key in dict[first_key]['subkey2'].keys()]
输出(从您的数据集):
[('keyA', 'A2a'), ('keyB', 'B2z'), ('keyB', 'B2e'), ('keyB', 'B2w'), ('keyC', 'C2a'), ('keyC', 'C2b')]
添加回答
举报
0/150
提交
取消