Need a strange sort method...
mensanator at aol.com
mensanator at aol.com
Mon Oct 16 16:45:17 EDT 2006
SpreadTooThin wrote:
> SpreadTooThin wrote:
> > Simon Brunning wrote:
> > > On 10/16/06, Simon Brunning <simon at brunningonline.net> wrote:
> > > > >>> a = [1,2,3,4,5,6,7,8,9,10]
> > > > >>> a.sort(key=lambda item: (((item-1) %3), item))
> > > > >>> a
> > > > [1, 4, 7, 10, 2, 5, 8, 3, 6, 9]
> > >
> > > Re-reading the OP's post, perhaps sorting isn't what's required:
> > >
> > > >>> a[::3] + a[1::3] + a[2::3]
> > > [1, 4, 7, 10, 2, 5, 8, 3, 6, 9]
> > >
> > > --
> > > Cheers,
> > > Simon B
> > > simon at brunningonline.net
> > > http://www.brunningonline.net/simon/blog/
> >
>
> > Ok so this is what I got.. but there is an odd side effect:
> >
> > def reslice(series):
> > series.sort()
> > i = 1
> > newseries = series[::3]
> > while(1):
> > c = series[i::3]
> > if len(c) >= 3:
> > newseries = newseries + c
> > else:
> > break
> > i = i + 1
> > return newseries
> >
> > a = [2,1,4,3,6,5,8,7,10,9]
> > b = reslice(a)
> > print b
> > >>> [1, 4, 7, 10, 2, 5, 8, 3, 6, 9, 4, 7, 10]
> >
> > I have one extra 10 that I shouldn't...
Actually, you have an extra 4,7,10.
>
>
> I think my loop termination is incorrect...
> maybe I should just stop when my new series size is the same size as
> the original?
You can do this automatically (and pass the size of the
desired sublist grouping also).
def strange(n,d):
""" n list to sort
d sublist length
"""
LoL = []
for i in xrange(d):
LoL.append(n[i::d])
print LoL
out = []
for i in LoL:
out.extend(i)
return out
a = [1,2,3,4,5,6,7,8,9,10]
b = [1,3,5,7,11,13,17,19,23,29]
c = [1,2,3,4,4,5,6,7,8,9,10]
d = [1,2]
print a
test = strange(a,3)
print test
print
print a
test = strange(a,4)
print test
print
print a
test = strange(a,5)
print test
print
print b
test = strange(b,3)
print test
print
print c
test = strange(c,3)
print test
print
print d
test = strange(d,5)
print test
print
## [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
## [[1, 4, 7, 10], [2, 5, 8], [3, 6, 9]]
## [1, 4, 7, 10, 2, 5, 8, 3, 6, 9]
##
## [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
## [[1, 5, 9], [2, 6, 10], [3, 7], [4, 8]]
## [1, 5, 9, 2, 6, 10, 3, 7, 4, 8]
##
## [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
## [[1, 6], [2, 7], [3, 8], [4, 9], [5, 10]]
## [1, 6, 2, 7, 3, 8, 4, 9, 5, 10]
##
## [1, 3, 5, 7, 11, 13, 17, 19, 23, 29]
## [[1, 7, 17, 29], [3, 11, 19], [5, 13, 23]]
## [1, 7, 17, 29, 3, 11, 19, 5, 13, 23]
##
## [1, 2, 3, 4, 4, 5, 6, 7, 8, 9, 10]
## [[1, 4, 6, 9], [2, 4, 7, 10], [3, 5, 8]]
## [1, 4, 6, 9, 2, 4, 7, 10, 3, 5, 8]
##
## [1, 2]
## [[1], [2], [], [], []]
## [1, 2]
More information about the Python-list
mailing list