[英]Using a nested list to create dictionary where first list is column and each list a row?
I have a nested loop that has the first list as column names and each subsequent list is a row.我有一个嵌套循环,其中第一个列表作为列名,每个后续列表都是一行。 For example, I have a nested list that gives a person's age and 1 or 0 indicating whether or not they like the color:
例如,我有一个嵌套列表,它给出了一个人的年龄和 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]
I want an output that looks like:我想要一个看起来像的 output:
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 .....}
etc but with all data.等,但所有数据。
I've gotten as far as:我已经做到了:
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
and when I try to combine t[0] and x as a tuple it ends up only giving me:当我尝试将 t[0] 和 x 组合为一个元组时,它最终只给了我:
{'12blue': 1, '10blue': 0, '9blue': 0, '8blue': 1, '13blue': 1}
{'12green': 0, '10green': 1, '9green': 0, '8green': 0, '13green': 1}
etc.等等
You could do the following:您可以执行以下操作:
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)
Output Output
{(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}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.