如何将元组列表转换为含specs和data键的字典
拆分元组列表为指定结构的字典
输入:
original_list = [(5, 10, 8, 2, 3, 12, 'first', 'second', 2, 80, 75, 'third'), (8, 2, 8, 14, 7, 3, 'name', 'last', 2, 80, 75, 'block')]
输出:
new = {'specs':[(5, 10, 8, 2, 3, 12), (8, 2, 8, 14, 7, 3)], 'data': [('first', 'second', 2, 80, 75, 'third'), ('name', 'last', 2, 80, 75, 'block')]}
需求说明
需将任意数量的元组组成的列表,拆分为包含两个键的字典:
- 'specs':对应的值为每个原元组前6个元素组成的元组列表
- 'data':对应的值为每个原元组剩余元素组成的元组列表
解决方案
利用Python的切片操作可以快速实现需求:
original_list = [(5, 10, 8, 2, 3, 12, 'first', 'second', 2, 80, 75, 'third'), (8, 2, 8, 14, 7, 3, 'name', 'last', 2, 80, 75, 'block')] new = { 'specs': [item[:6] for item in original_list], 'data': [item[6:] for item in original_list] } print(new)
代码解释
item[:6]截取每个元组的前6个元素,生成新元组,遍历所有元组后得到specs对应的列表item[6:]截取每个元组从第7个元素开始的剩余部分,遍历所有元组后得到data对应的列表- 该方法简洁高效,无论原列表包含多少个元组都能正常工作
内容的提问来源于stack exchange,提问作者thisisjustme
相关产品推荐
相关产品推荐

