[Tutor] split a tuple
János Juhász
janos.juhasz at VELUX.com
Thu Nov 17 16:46:37 CET 2005
Hi Chris,
Thanks your response.
I have just found another way.
>>> import math
>>> l = (1,2,3,4,5,1,2,3,4,5,1,2,3,4,5)
>>> n = 4
>>> extended = l + ('default',)*int(n - math.fmod(len(l),n))
>>> [extended[i:i+n] for i in range(0,len(extended),n)]
[(1, 2, 3, 4), (5, 1, 2, 3), (4, 5, 1, 2), (3, 4, 5, 'default')]
>>>| Hi,
>>>|
>>>| I couldn't get idea how to make the next thing
>>>|
>>>|||| n=4 #split into so long parts
>>>|||| l = (1,2,3,4,5,1,2,3,4,5,1,2,3,4,5) #this is the tuple to split
>>>|||| [l[i:i+n] for i in range(0,len(l),n)]
>>>| [(1, 2, 3, 4), (5, 1, 2, 3), (4, 5, 1, 2), (3, 4, 5)]
>>>|
>>>| But I have to make it like this
>>>| [(1, 2, 3, 4), (5, 1, 2, 3), (4, 5, 1, 2), (3, 4, 5, default)]
>>>| because i use it later in this
>>>|
>>>|||| result = [l[i:i+n] for i in range(0,len(l),n)]
>>>|||| zip(*result)
>>>| [(1, 5, 4, 3), (2, 1, 5, 4), (3, 2, 1, 5)]
>>>|
>>>| and as you can see it, the last element is missing here.
>>>|
>>>
>>>Since it will always be the last one that is not the correct length; can
you just add another line to extend the >>>length of the last one by the
correct number of default values (that number being the difference between
how many >>>you want and how many you have)?
>>>
>>>######
>>>>>> l = (1,2,3,4,5,1,2,3,4,5,1,2,3,4,5)
>>>>>> n=4
>>>>>> regrouped = [l[i:i+n] for i in range(0,len(l),n)]
>>>>>> default = 'default'
>>>>>> regrouped[-1]=list(regrouped[-1])
>>>>>> regrouped[-1].extend([default]*(n-len(regrouped[-1])))
>>>>>> regrouped[-1]=tuple(regrouped[-1])
>>>>>> regrouped
>>>[(1, 2, 3, 4), (5, 1, 2, 3), (4, 5, 1, 2), (3, 4, 5, 'default')]
>>>>>>
>>>>>> ['a']*3 #so you can see what the rhs multiply does
>>>['a', 'a', 'a']
>>>
>>>######
>>>
>>>Since tuples cannot be changed, you have to go through the tuple<->list
conversion steps. If you can work with a >>>list instead, then these two
steps could be eliminated:
>>>
>>>######
>>>>>> l = [1,2,3,4,5,1,2,3,4,5,1,2,3,4,5] #using a list instead
>>>>>> regrouped = [l[i:i+n] for i in range(0,len(l),n)]
>>>>>> regrouped[-1].extend([default]*(n-len(regrouped[-1])))
>>>>>> regrouped
>>>[[1, 2, 3, 4], [5, 1, 2, 3], [4, 5, 1, 2], [3, 4, 5, 'default']]
>>>>>>
>>>######
>>>
>>>/c
Yours sincerely,
______________________________
János Juhász
More information about the Tutor
mailing list