我有一个列表,其中包含像这样的json对象
a =[{"User": "Ram","Product": "Soap","Price": "25"},
{"User": "Ramesh","Product": "Shampoo","Price": "5"},
{"User": "Ramesh","Product": "powder","Price": "35"}]
现在,我想将此单个列表拆分为多个列表,如此
a2 = [
[{"User": "Ram","Product": "Soap","Price": "25"}],
[{"User": "Ramesh","Product": "Shampoo","Price": "5"}],
[{"User": "Ramesh","Product": "powder","Price": "35"}]
]
任何人都可以告诉我如何实现这个解决方案,我是python的新手。
答案 0 :(得分:3)
这样做,
[[i] for i in a]
答案 1 :(得分:3)
将每个项目用括号括起来:
a2 = [[item] for item in a]
答案 2 :(得分:0)
另一种解决方案,
new_a = map(lambda x: [x], a)
输出
[[{'Product': 'Soap', 'User': 'Ram', 'Price': '25'}], [{'Product': 'Shampoo', 'User': 'Ramesh', 'Price': '5'}], [{'Product': 'powder', 'User': 'Ramesh', 'Price': '35'}]]
答案 3 :(得分:-1)
如果没有Avinash答案中的列表理解,这是一种更冗长的方式。
def list_split(a):
sp = []
for element in a:
sp.append([element])
return sp
a2 = list_split(a)