Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better Way to Write This List Comprehension?

I'm parsing a string that doesn't have a delimiter but does have specific indexes where fields start and stop. Here's my list comprehension to generate a list from the string:

field_breaks = [(0,2), (2,10), (10,13), (13, 21), (21, 32), (32, 43), (43, 51), (51, 54), (54, 55), (55, 57), (57, 61), (61, 63), (63, 113), (113, 163), (163, 213), (213, 238), (238, 240), (240, 250), (250, 300)]
s = '4100100297LICACTIVE  09-JUN-198131-DEC-2010P0         Y12490227WYVERN RESTAURANTS INC                            1351 HEALDSBURG AVE                                                                                 HEALDSBURG               CA95448     ROUND TABLE PIZZA                                 575 W COLLEGE AVE                                 STE 201                                           SANTA ROSA               CA95401               '
data = [s[x[0]:x[1]].strip() for x in field_breaks]

Any recommendation on how to improve this?

like image 681
Derek Swingley Avatar asked Jan 20 '26 14:01

Derek Swingley


2 Answers

You can cut your field_breaks list in half by doing:

field_breaks = [0, 2, 10, 13, 21, 32, 43, ..., 250, 300]
s = ...
data = [s[x[0]:x[1]].strip() for x in zip(field_breaks[:-1], field_breaks[1:])]
like image 66
dan04 Avatar answered Jan 22 '26 02:01

dan04


You can use tuple unpacking for cleaner code:

data = [s[a:b].strip() for a,b in field_breaks]
like image 41
Tomasz Wysocki Avatar answered Jan 22 '26 04:01

Tomasz Wysocki