python - Splitting data - specific case -


i'm trying split data, data in form...

['20150406,34.4800,34.8100,34.2300,34.4200,21480500', '20150407,34.5400,34.8900,34.5100,34.6300,14331200'] 

the first item in each string in list date, trying split data @ chosen date. have whole string... example if chosen date 2015-04-07 above data split this...

['20150406,34.4800,34.8100,34.2300,34.4200,21480500']  ['20150407,34.5400,34.8900,34.5100,34.6300,14331200'] 

this has work lists lots of strings in same form this...

use next() , enumerate() find position of string desired date, slice:

>>> d = '20150407' >>> l = [ ...     '20150406,34.4800,34.8100,34.2300,34.4200,21480500', ...     '20160402,34.1,32.8100,33.2300,31.01,22282510', ...     '20150407,34.5400,34.8900,34.5100,34.6300,14331200', ...     '20120101,2.540,14.8201,32.00,30.1311,12331230' ... ] >>> index = next(i i, item in enumerate(l) if item.startswith(d)) >>> l[:index] ['20150406,34.4800,34.8100,34.2300,34.4200,21480500', '20160402,34.1,32.8100,33.2300,31.01,22282510'] >>> l[index:] ['20150407,34.5400,34.8900,34.5100,34.6300,14331200', '20120101,2.540,14.8201,32.00,30.1311,12331230'] 

couple notes:

  • next() through stopiteration exception if there no match - should either handle try/except or provide default value, -1 example:

    next((i i, item in enumerate(l) if item.startswith(d)), -1) 
  • to check if date matches desired one, checking if item starts specific date string. if desired date comes date or datetime, need format beforehand using strftime():

    >>> datetime import datetime >>> d = datetime(2015, 4, 7) >>> d = d.strftime("%y%m%d") >>> d '20150407' 

Comments