如果像你说的,你有一个列表的列表,即
data = [
['Metric', 'Person1', 'Person2', 'Person3', 'Person4'],
['Sex|Male', 0.5, 0.75, 0.35, 0.8],
['Sex|Female', 0, 50, 0.25, 0.65, 0.2],
['Age| 18-24', 0.25, 0.2, 0.15, 0.17],
]
下面将产生所需的输出:
>>> l = zip(*data) # swap rows and columns - it's easier to work this way
>>> from pprint import pprint
>>> pprint(l)
[('Metric', 'Sex|Male', 'Sex|Female', 'Age| 18-24'),
('Person1', 0.5, 0, 0.25),
('Person2', 0.75, 50, 0.2),
('Person3', 0.35, 0.25, 0.15),
('Person4', 0.8, 0.65, 0.17)]
>>> result = []
>>> for row in l[1:]:
... result.append({row[0] : [{l[0][i] : row[i]} for i in range(1, len(row))]})
>>> pprint(result)
[{'Person1': [{'Sex|Male': 0.5}, {'Sex|Female': 0}, {'Age| 18-24': 0.25}]},
{'Person2': [{'Sex|Male': 0.75}, {'Sex|Female': 50}, {'Age| 18-24': 0.2}]},
{'Person3': [{'Sex|Male': 0.35}, {'Sex|Female': 0.25}, {'Age| 18-24': 0.15}]},
{'Person4': [{'Sex|Male': 0.8}, {'Sex|Female': 0.65}, {'Age| 18-24': 0.17}]}]
通常PERSON1,PERSON2 ..不列,但线。你确认了吗? – user3378649 2014-10-20 03:04:49
尝试显示是列表的形式。是[[公制,Person1,Person2,Person3,Person4,] ..]还是[[公制,性别|男性,性别|女性,年龄] ..]。我的意思是,你正在采取horozantally还是垂直? – user3378649 2014-10-20 03:09:07