我有一个嵌套循环,该循环具有第一个列表作为列名,而每个后续列表都是一行。例如,我有一个嵌套列表,其中列出了一个人的年龄以及1或0,表示他们是否喜欢该颜色:
data = [['age', 'blue', 'green', 'red', 'orange'],
[12, 1, 0, 0, 1],
[10, 0, 1, 0, 1],
[9, 0, 0, 0, 0],
[8, 1, 0, 0, 0],
[13, 1, 1, 1, 0]
我想要的输出看起来像:
new_data ={(12, 'blue'): 1,
(12, 'green'): 0,
(12, 'red'): 0,
(12, 'orange'): 1,
(9, 'blue'): 0,
(9, 'green'): 1,
(9, 'red'): 0,
(9, 'orange'): 1 .....}
等,但包含所有数据。
我已经做到了:
ages = data[0][1:len(data[0])]
i = 1
for x in ages:
print({t[0] + x: t[i] for t in data[1:len(data)]})
i = i + 1
当我尝试将t [0]和x合并为元组时,它最终只会给我:
{'12blue': 1, '10blue': 0, '9blue': 0, '8blue': 1, '13blue': 1}
{'12green': 0, '10green': 1, '9green': 0, '8green': 0, '13green': 1}
等
答案 0 :(得分:1)
您可以执行以下操作:
import pprint
data = [['age', 'blue', 'green', 'red', 'orange'],
[12, 1, 0, 0, 1],
[10, 0, 1, 0, 1],
[9, 0, 0, 0, 0],
[8, 1, 0, 0, 0],
[13, 1, 1, 1, 0]]
colors, *rows = data # split in colors and rows
d = {}
for row in rows:
idi, *marks = row # split in id and marks
for color, mark in zip(colors[1:], marks): # iterate in parallel over marks and colors
d[(idi, color)] = mark
pprint.pprint(d)
输出
{(8, 'blue'): 1,
(8, 'green'): 0,
(8, 'orange'): 0,
(8, 'red'): 0,
(9, 'blue'): 0,
(9, 'green'): 0,
(9, 'orange'): 0,
(9, 'red'): 0,
(10, 'blue'): 0,
(10, 'green'): 1,
(10, 'orange'): 1,
(10, 'red'): 0,
(12, 'blue'): 1,
(12, 'green'): 0,
(12, 'orange'): 1,
(12, 'red'): 0,
(13, 'blue'): 1,
(13, 'green'): 1,
(13, 'orange'): 0,
(13, 'red'): 1}