小编cod*_*e47的帖子

将可变长度元组列表转换为字典

我有一个可变长度元组列表.如何将其转换为字典?

tup = [ ("x", 1), ("x", 2, 4), ("x", 3), ("y", 1), ("y", 2), ("z", 1), ("z", 2, 3) ]  
Run Code Online (Sandbox Code Playgroud)

使用理解时,我得到以下错误

{key: [i[1:] for i in tup if i[0] == key] for (key, value) in tup}  
Run Code Online (Sandbox Code Playgroud)

错误:

ValueError
Traceback (most recent call last)
>ipython-input-26-bedcc2e8a704< in module()
----> 1 {key: [i[1] for i in tuplex if i[0] == key] for (key, value) in tuplex}  
>ipython-input-26-bedcc2e8a704< in dictcomp((key, value))
----> 1 {key: [i[1] for i in tuplex if i[0] == key] …
Run Code Online (Sandbox Code Playgroud)

python python-2.7 python-3.x

3
推荐指数
1
解决办法
198
查看次数

标签 统计

python ×1

python-2.7 ×1

python-3.x ×1