Python:按类型将长度为n的列表拆分为一个表或更多的列表,保留ord

2024-09-25 08:24:49 发布

您现在位置:Python中文网/ 问答频道 /正文

本质上,我有一个不同类型的项目列表,比如

['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。在

我这样做的原因是我将得到一个包含不同类型信息的列表,并且需要用其他值来充实它,以补充原始列表。在

有更好的方法吗?在


Tags: 项目innone类型列表for顺序def
3条回答

在这里,我可能会使用defaultdict稍微不同的方法:

from collections import defaultdict
def type_split(sources):
   d=defaultdict(lambda : [None]*len(sources))
   for i,src in enumerate(sources):
       d[type(src)][i] = src
   return d

这将返回一个字典而不是一个列表,但是更容易反省各种元素的类型……如果您真的想要列表,您可以随时查看d.values()(在python2.x中)或{}在python3.x中

@mgilson对解决方案的一种改编,它将类型的原始顺序保持为有序键。在

>>> from collections import OrderedDict
>>> def type_split(seq):
        d = OrderedDict()
        for i, x in enumerate(seq):
            d.setdefault(type(x), [None] * len(seq))[i] = x
        return d.values()

>>> type_split(['a',1,'b',2,3,'c'])
[['a', None, 'b', None, None, 'c'], [None, 1, None, 2, 3, None]]
>>> type_split([{"A":1},1,{"B":2},{"C":3},"a"])
[[{'A': 1}, None, {'B': 2}, {'C': 3}, None], [None, 1, None, None, None], [None, None, None, None, 'a']]

这是条件表达式的一个很好的用例。另外,我假设您希望以尽可能通用的方式来执行此操作,因此我建议您动态生成列表,而不是使用固定的类型列表:

def type_split(sources):
    types = sorted(set(type(i) for i in sources))
    return [[item if type(item) == itype else None for item in sources] 
            for itype in types]  

如果您需要使用一个固定列表(并且您知道您的输入列表只包含这些类型及其子类),您可以这样做:

^{pr2}$

相关问题 更多 >