You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将值为列表的字典转换为展开元素的元组列表?

字典转指定格式元组列表的正确实现

你需要将字典{1: ['a', 'b', 'c', 'd'], 2: ['e', 'f', 'g', 'h']}转换为[(1, 'a', 'b', 'c', 'd'), (2, 'e', 'f', 'g', 'h')]的元组列表,当前代码:

dictionary = {1: ['a', 'b', 'c', 'd'], 2: ['e', 'f', 'g', 'h']}

list_of_tuples = [(k, v) for k, v in dictionary.items()]

得到的结果是[(1, ['a', 'b', 'c', 'd']), (2, ['e', 'f', 'g', 'h'])],未达到预期。

正确实现方法

方法1:使用解包语法(Python 3.5+)

利用*运算符将列表元素直接展开到元组中:

dictionary = {1: ['a', 'b', 'c', 'd'], 2: ['e', 'f', 'g', 'h']}

list_of_tuples = [(k, *v) for k, v in dictionary.items()]

执行后即可得到目标格式的元组列表。

方法2:元组拼接(兼容旧版Python)

如果你的Python版本不支持解包语法,可以通过元组拼接实现:

dictionary = {1: ['a', 'b', 'c', 'd'], 2: ['e', 'f', 'g', 'h']}

list_of_tuples = [(k,) + tuple(v) for k, v in dictionary.items()]

这里(k,)创建仅包含键的单元素元组,再与转换为元组的列表tuple(v)拼接,同样能得到预期结果。

内容的提问来源于stack exchange,提问作者Zelimir_Horvat_CRO

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 23:20:59