Featured post
python - Creating sublists -
the opposite of list flattening.
given list , length n return list of sub lists of length n.
def sublist(lst, n): sub=[] ; result=[] in lst: sub+=[i] if len(sub)==n: result+=[sub] ; sub=[] if sub: result+=[sub] return result
an example:
if list is:
[1,2,3,4,5,6,7,8]
and n is:
3
return:
[[1, 2, 3], [4, 5, 6], [7, 8]]
is there more eloquent / concise way?
an aside, preferred when appending lists lists (in context above):
list1+=[list2]
or:
list1.append(list2)
given (according summerfeild's 'programming in python 3') same?
thanks.
such list of lists constructed using list comprehension:
in [17]: seq=[1,2,3,4,5,6,7,8] in [18]: [seq[i:i+3] in range(0,len(seq),3)] out[18]: [[1, 2, 3], [4, 5, 6], [7, 8]]
there grouper idiom:
in [19]: import itertools in [20]: list(itertools.izip_longest(*[iter(seq)]*3)) out[20]: [(1, 2, 3), (4, 5, 6), (7, 8, none)]
but note missing elements filled value none. izip_longest can take fillvalue
parameter if other none desired.
list1+=[list2]
-- noting brackets time -- equivalent list1.append(list2)
. highest priority when writing code readability, not speed. reason, go list1.append(list2)
. readability subjective, however, , influenced idioms you're familiar with.
happily, in case, readability , speed seem coincide:
in [41]: %timeit list1=[1,2,3]; list1.append(list2) 1000000 loops, best of 3: 612 ns per loop in [42]: %timeit list1=[1,2,3]; list1+=[list2] 1000000 loops, best of 3: 847 ns per loop
- Get link
- X
- Other Apps
Comments
Post a Comment