嵌套循环和列表的克隆
Nested loops and cloning of lists
我有一个字典列表
lst = [{"activity":"tx"},{"activity":"fl", "ids":['123','456','789','432']}, {"activity":"ia"}]
我想克隆这些列表并将它们添加到主列表中,其中的数字基于“fl”字典中唯一的“ids”。
期望的结果:
master = [[{"activity":"tx"},{"activity":"fl", "ids":'123'}, {"activity":"ia"}],
[{"activity":"tx"},{"activity":"fl", "ids":'456'}, {"activity":"ia"}],
[{"activity":"tx"},{"activity":"fl", "ids":'789'}, {"activity":"ia"}],
[{"activity":"tx"},{"activity":"fl", "ids":'432'}, {"activity":"ia"}]]
这可以通过 lst[1]['ids']
上的一个简单循环来完成
ans = [[lst[0], {"activity":"fl", "ids": id}, lst[2]] for id in lst[1]['ids']]
print(ans)
[[{'activity': 'tx'}, {'activity': 'fl', 'ids': '123'}, {'activity': 'ia'}],
[{'activity': 'tx'}, {'activity': 'fl', 'ids': '456'}, {'activity': 'ia'}],
[{'activity': 'tx'}, {'activity': 'fl', 'ids': '789'}, {'activity': 'ia'}],
[{'activity': 'tx'}, {'activity': 'fl', 'ids': '432'}, {'activity': 'ia'}]]
我有一个字典列表
lst = [{"activity":"tx"},{"activity":"fl", "ids":['123','456','789','432']}, {"activity":"ia"}]
我想克隆这些列表并将它们添加到主列表中,其中的数字基于“fl”字典中唯一的“ids”。
期望的结果:
master = [[{"activity":"tx"},{"activity":"fl", "ids":'123'}, {"activity":"ia"}],
[{"activity":"tx"},{"activity":"fl", "ids":'456'}, {"activity":"ia"}],
[{"activity":"tx"},{"activity":"fl", "ids":'789'}, {"activity":"ia"}],
[{"activity":"tx"},{"activity":"fl", "ids":'432'}, {"activity":"ia"}]]
这可以通过 lst[1]['ids']
ans = [[lst[0], {"activity":"fl", "ids": id}, lst[2]] for id in lst[1]['ids']]
print(ans)
[[{'activity': 'tx'}, {'activity': 'fl', 'ids': '123'}, {'activity': 'ia'}],
[{'activity': 'tx'}, {'activity': 'fl', 'ids': '456'}, {'activity': 'ia'}],
[{'activity': 'tx'}, {'activity': 'fl', 'ids': '789'}, {'activity': 'ia'}],
[{'activity': 'tx'}, {'activity': 'fl', 'ids': '432'}, {'activity': 'ia'}]]