Essentially I have a list of items each with a different type such as
['a',1,'b',2,3,'c']
or
[{"A":1},1,{"B":2},{"C":3},"a"]
and I would like to split these into two seperate lists, retaining the original order
[[ 'a', None, 'b', None, None, 'c'],
[None, 1, None, 2, 3, None]]
or
[[{"A":1}, None, {"B":2},{"C":3}, None],
[None, 1, None, None, None],
[None, None, None, None, "a"]]
What I have :
def TypeSplit(sources)
Types = [dict(),str(),num()]
return [[item for item in sources if type(item) == type(itype)] for itype in types]
Though this doesn’t fill in None.
The reason I’m doing this is that I will be given a list with different types of info and need to flesh it out with other values that compliment the original list.
Is there a better way to do this ?
This is a good use-case for the conditional expression. Also, I’m assuming you’d like to do this in as generalized a way as possible, so instead of using a fixed list of types, I’d suggest generating the list dynamically:
If you need to use a fixed list (and you know that your input list won’t contain anything but those types and their subclasses), you could do this: