0

I have the following list:

a = [1104537600, 1199145600, False, 1199145600, 1443886293, True]

and I want to split this list to two sublists such as:

[[1104537600, 1199145600,1199145600, 1443886293],[False,True]]

I am using the following which give that result:

b = [value for value in a if type(value) is int]
c = [value for value in a if type(value) is bool]
d = [b,c]

But is there a more elegant way? In one line?

Mpizos Dimitris
  • 4,819
  • 12
  • 58
  • 100

4 Answers4

3

Your attempt is pretty and understandable ,more of it you can combine both ur b and c in only one statement as :

d=[[value for value in a if type(value) is bool ],[value for value in a if type(value) is int ]]
nsr
  • 855
  • 7
  • 10
1

Use the traditional for loop. By this way, you don't need to iterate over the same list for two times.

>>> num, b = [], []
>>> for i in a:
    if type(i) is int:
        num.append(i)
    elif type(i) is bool:
        b.append(i)


>>> num
[1104537600, 1199145600, 1199145600, 1443886293]
>>> b
[False, True]
>>> [num, b]
[[1104537600, 1199145600, 1199145600, 1443886293], [False, True]]
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
  • But is it more elegant? Safe very extreme cases, it won't matter for performance if you iterate it once or twice. – wvdz Mar 08 '16 at 09:07
0

I guess doing it in one line would be less elegant actually. Keep in mind that the most important - if we don't consider performances - is that someone (or you in the future) can easily understand your code.

This one is easily understandable, and not wrong, I would go for it for sure

pltrdy
  • 2,069
  • 1
  • 11
  • 29
0

You could build the d list up as follows:

a = [1104537600, 1199145600, False, 1199145600, 1443886293, True]
d = [[], []]

for value in a:
    if type(value) is int:
        d[0].append(value)
    elif type(value) is bool:
        d[1].append(value)    

print d  

Giving:

[[1104537600, 1199145600, 1199145600, 1443886293], [False, True]]
Martin Evans
  • 45,791
  • 17
  • 81
  • 97