我需要将嵌套列表result = [[450, 455, 458], [452, 454, 457], [451, 453]]
转换为类似
{
0:
{
450: None,
455: 450,
458: 450
},
1: {
452: None,
454: 452,
456: 452,
457: 452
},
2: {
451: None,
453: 451
}
}
请看一下并提供帮助:
result_group = {}
for sub_group in result:
group_count = 0
first_rel_item = 0
result_group[group_count] = dict()
for item in sub_group:
if item == sub_group[0]:
result_group[group_count][item] = None
first_rel_item = item
continue
result_group[group_count]['item'] = first_rel_face
group_count += 1
当我得到密钥时,我搞砸了这个错误:1无法添加到字典中。
答案 0 :(得分:3)
这是一种方式:
lst = [[450, 455, 458], [452, 454, 457], [451, 453]]
res = {i: {w: None if w == v[0] else v[0] for w in v}
for i, v in enumerate(lst)}
<强>结果强>
{0: {450: None, 455: 450, 458: 450},
1: {452: None, 454: 452, 457: 452},
2: {451: None, 453: 451}}
<强>解释强>
None
还是v[0]
。enumerate
提取嵌套列表的索引。答案 1 :(得分:1)
试试这个:
result_group = {}
group_count = 0
for sub_group in result:
first_rel_item = 0
result_group[group_count] = {}
result_group[group_count][sub_group[0]] = None
previtem = sub_group[0]
for item in sub_group[1:]:
result_group[group_count][item] = previtem
group_count += 1
答案 2 :(得分:1)
你可以在这里使用列表理解:
>>> result = [[450, 455, 458], [452, 454, 457], [451, 453]]
>>> dict(enumerate({**{i: a[0] for i in a[1:]}, **{a[0]: None}}
for a in result))
{0: {450: None, 455: 450, 458: 450},
1: {452: None, 454: 452, 457: 452},
2: {451: None, 453: 451}}
注意:这使用了"extended"可迭代的解包,这是在Python 3.5中引入的。 z = {**x, **y}
合并了词典x
和y
。
每个a
都是result
的子列表。您希望使用a[0]
作为第1个元素及以上的值,并使用None作为第0个元素。
这里的假设是您只希望子列表的第0个元素具有相应的None值。 (如果第0个元素重复,在某处,它将使用第0个元素作为其值,如@jpp的答案。)
答案 3 :(得分:0)
# the nice solutions were already given, so by foot:
d = {}
result = [[450, 455, 458], [452, 454, 457], [451, 453]]
for idx,l in enumerate(result): # returns the index and the sublists data
rMin = min(l)
d[idx] = {} # create a inner dict at key idx
for i in l:
d[idx][i] = None if i == rMin else rMin # fill inner dicts keys
print(d)
输出:
{0: {450: None, 455: 450, 458: 450},
1: {452: None, 454: 452, 457: 452},
2: {451: None, 453: 451}}