重塑python中的不规则列表 [英] reshape an irregular list in python
本文介绍了重塑python中的不规则列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想重塑以下列表:
wide_list = [[1,['a','b','c']],[2,['d','e']],[3,'f']]
长格式":
long_list = [[1,'a'],[1,'b'],[1,'c'],[2,'d'],[2,'e'],[3,'f']]
如何在Python中有效地实现这一目标?
How can this be achieved efficiently in Python?
推荐答案
尝试嵌套列表理解:
>>> wide_list = [[1,['a','b','c']],[2,['d','e']],[3, ['f']]]
>>> long_list = [[k, v] for k, sublist in wide_list for v in sublist]
>>> long_list
[[1, 'a'], [1, 'b'], [1, 'c'], [2, 'd'], [2, 'e'], [3, 'f']]
请注意,最后一组必须更改为匹配前两组的模式.代替 [3,'f']
,而使用 [3,['f']]
.否则,对于不遵循该模式的组,您将需要特殊情况逻辑.
Note, the last group had to be changed to match the pattern of the first two groups. Instead of [3, 'f']
, use [3, ['f']]
instead. Otherwise, you'll need special case logic for groups that don't follow the pattern.
这篇关于重塑python中的不规则列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文