Is there an easier way to express this list slicing?
Thomas.Ploch at gmx.net
Thu Nov 30 21:07:10 CET 2006
John Henry schrieb:
> If I have a list of say, 10 elements and I need to slice it into
> irregular size list, I would have to create a bunch of temporary
> variables and then regroup them afterwords, like:
> # Just for illustration. Alist can be any existing 10 element list
> That obviously work but do I *really* have to do that?
> BTW: I know you can do:
> but I don't see that it's any better.
> Can I say something to the effect of:
> (a,b,c[0:2],d[0:5])=a_list # Obviously this won't work
> I am asking this because I have a section of code that contains *lots*
> of things like this. It makes the code very unreadable.
I had a little bit of fun while writing this:
itemList = (a,b,c1,c2,c3,d1,d2,d3,d4,d5) and
itemList2 = (a1,a2,a3,b,c,d1,d2,d3,d4,d5) the next time.
def getSlices(aCount, bCount, cCount, dCount, items):
a,b,c,d = (items[0:aCount],
>>>a,b,c,d = getSlices(1,1,3,5,itemList)
['a'] ['b'] ['c1', 'c2', 'c3'] ['d1', 'd2', 'd3', 'd4', 'd5']
>>>a,b,c,d = getSlices(3,1,1,0,itemList2)
['a1', 'a2', 'a3'] ['b'] ['c'] 
More information about the Python-list