本质上,我有一个不同类型的项目列表,比如
['a',1,'b',2,3,'c']
或者
^{pr2}$我想把它们分成两个单独的列表,保持原来的顺序
[[ 'a', None, 'b', None, None, 'c'],
[None, 1, None, 2, 3, None]]
或者
[[{"A":1}, None, {"B":2},{"C":3}, None],
[None, 1, None, None, None],
[None, None, None, None, "a"]]
我所拥有的:
def TypeSplit(sources)
Types = [dict(),str(),num()]
return [[item for item in sources if type(item) == type(itype)] for itype in types]
虽然这并没有填充None
。在
我这样做的原因是我将得到一个包含不同类型信息的列表,并且需要用其他值来充实它,以补充原始列表。在
有更好的方法吗?在
在这里,我可能会使用
defaultdict
稍微不同的方法:这将返回一个字典而不是一个列表,但是更容易反省各种元素的类型……如果您真的想要列表,您可以随时查看}在python3.x中
d.values()
(在python2.x中)或{@mgilson对解决方案的一种改编,它将类型的原始顺序保持为有序键。在
这是条件表达式的一个很好的用例。另外,我假设您希望以尽可能通用的方式来执行此操作,因此我建议您动态生成列表,而不是使用固定的类型列表:
如果您需要使用一个固定列表(并且您知道您的输入列表只包含这些类型及其子类),您可以这样做:
^{pr2}$相关问题 更多 >
编程相关推荐