Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiomatic way to unpack variable length list of maximum size n

I'm reading a file and unpacking each line like this:

for line in filter(fh):
  a, b, c, d = line.split()

However, it's possible that line may have more or fewer columns than the variables I wish to unpack. In the case when there are fewer, I'd like to assign None to the dangling variables, and in the case where there are more, I'd like to ignore them. What's the idiomatic way to do this? I'm using python 2.7.

like image 275
pythonic metaphor Avatar asked Dec 10 '13 17:12

pythonic metaphor


2 Answers

Fix the length of the list, padding with None.

def fixLength(lst, length):
    return (lst + [None] * length)[:length]
like image 69
Hyperboreus Avatar answered Oct 17 '22 04:10

Hyperboreus


In python 3 you can use this

a, b, c, d, *_unused_ = line.split() + [None]*4

Edit

For large strings I suggest to use maxsplit-argument for split (this argument also works in py2.7):

a, b, c, d, *_unused_ = line.split(None, 4) + [None]*4

Why 5? Otherwise the 4th element would consist the whole residual of the line.

Edit2 It is 4… It stops after 4 splits, not 4 elements

like image 7
koffein Avatar answered Oct 17 '22 03:10

koffein