我正试图在数据中进行随机选择,但当使用for循环将所有数据嵌套到数组中时,我被卡住了。
data = [
{"Animal1": "Dog", "Animal2": "Cat", "Animal3": "Snake"},
{"Animal1": "Mouse", "Animal2": "Ant", "Animal3": "Chicken"},
{"Animal1": "Fish", "Animal2": "Elephant", "Animal3": "Fox"},
{"Animal1": "rabbit", "Animal2": "sheep", "Animal3": "wolf"}
]
我的代码:
new_data = []
for rows in data:
for row in rows:
new_data.append(row)
print(new_data)
['Animal1', 'Animal2', 'Animal3', 'Animal1', 'Animal2', 'Animal3', 'Animal1', 'Animal2', 'Animal3', 'Animal1', 'Animal2', 'Animal3']
预期输出
{
"Animal1": "Dog", "Animal2": "Cat", "Animal3": "Snake",
"Animal1": "Mouse", "Animal2": "Ant", "Animal3": "Chicken",
"Animal1": "Fish", "Animal2": "Elephant", "Animal3": "Fox",
"Animal1": "rabbit", "Animal2": "sheep", "Animal3": "wolf"
}
我想你在找这样的东西:
from collections import defaultdict
results = defaultdict(list)
for rows in data:
for key, value in rows.items():
results[key].append(value)