Python字典单键多值pai

2024-04-23 08:41:47 发布

您现在位置:Python中文网/ 问答频道 /正文

Dict= [('or', []), ('and', [5, 12]), ('with', [9])]

这是一个单键多值对。你知道吗

我想把512分别分配给'and'。你知道吗

期望输出

[('or', []), ('and', [5]), ('and',[12]), ('with', [9])]

如何进行? 而且,我想让这个一般喜欢的长度也能超过2。你知道吗


Tags: orandwithdict单键
3条回答

你可以试试这个:

d= [('or', []), ('and', [5, 12]), ('with', [9])]
new_d = [g for h in [[i] if len(i[-1]) < 2 else [(i[0], c) for c in i[-1]] for i in d] for g in h]

输出:

[('or', []), ('and', 5), ('and', 12), ('with', [9])]

在给出的答案中添加一些更有趣的内容: 如果你不在乎顺序,你可以这样做:

transf_dict = [(x[0],y) for x in Dict for y in x[1]] + [(x[0],[])  for x in Dict if not x[1]]

你也可以把你的dict转换成一本真正的字典

newdict = dict(Dict)

我想,这会让东西更具可读性。例如:

transf_dict = []
for key,item in newdict.items():
    if not item:
        transf_dict.append((key,[]))
    else:
        transf_dict.extend([(key,[x]) for x in item])

会给你想要的产量,但都是以订购为代价的。如果您想稍微更改一下格式,请尝试:

transf_dict = [(x, lst) for x, y in Dict for lst in (y if y else [[]])]

我会用一个好的循环。一份清单的理解是如此复杂,恐怕最终会让人无法理解。你知道吗

data = [('or', []), ('and', [5, 12]), ('with', [9])]

res = []
for k, v in data:
    if len(v)>1:
        for r in v:
            res.append((k, [r]))
    else:
        res.append((k, v))
print(res)

产生:

[('or', []), ('and', [5]), ('and', [12]), ('with', [9])]

相关问题 更多 >