Venkatesh
Venkatesh

Reputation: 133

How to flatten a list of lists containing dates in Python

I have a list of valid dates in Python

   myList =['05-06-2015', '01-07-2015', '01-07-2015 01-07-2016',   '26-08-2015', '26-08-2016', '23-06-2015 26-08-2016 01-07-2015',   '06-07-2015'] 

As you can see, some elements have a single value, some have two and some have three dates.

My problem is to reduce all of these into a flattened list, which looks like this:

    flatList =['05-06-2015', '01-07-2015', '01-07-2015', '01-07-2016',  
 '26-08-2015', '26-08-2016', '23-06-2015', '26-08-2016', '01-07-2015',  
 '06-07-2015']  

I tried to do this:

flatList  = list(itertools.chain.from_iterable(myList))

But, this is not behaving as I expected and it is splitting each character as a list.

Can you please let me know how I can accomplish this?

Expected output:

    flatList =['05-06-2015', '01-07-2015', '01-07-2015', '01-07-2016',  
 '26-08-2015', '26-08-2016', '23-06-2015', '26-08-2016', '01-07-2015',  
 '06-07-2015']  

Upvotes: 1

Views: 162

Answers (3)

Vlad Bezden
Vlad Bezden

Reputation: 89587

from itertools import chain

my_list = [
    '05-06-2015', '01-07-2015', '01-07-2015 01-07-2016', '26-08-2015',
    '26-08-2016', '23-06-2015 26-08-2016 01-07-2015', '06-07-2015'
]

flat_list = list(chain(*[x.split() for x in my_list]))

print(flat_list)

output:

['05-06-2015', '01-07-2015', '01-07-2015', '01-07-2016', '26-08-2015', '26-08-2016', 
'23-06-2015', '26-08-2016', '01-07-2015', '06-07-2015']

Upvotes: 0

TerryA
TerryA

Reputation: 59974

You can split each element and then flatten the 2D list you'll have as a result, or if you want to avoid having to do the flatten bit, you could make your own loop:

newList = []
for i in myList:
    newList.extend(i.split())

Although I'd like to think that this isn't very pythonic - but it's an answer none-the-less.

Upvotes: 1

AChampion
AChampion

Reputation: 30258

You need to split each element in your original list and then flatten, e.g.:

In []:
list(it.chain.from_iterable(s.split() for s in myList)

Out[]:
['05-06-2015', '01-07-2015', '01-07-2015', '01-07-2016', '26-08-2015',
 '26-08-2016', '23-06-2015', '26-08-2016', '01-07-2015', '06-07-2015']

Upvotes: 3

Related Questions