473,946 Members | 3,146 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Is there an easier way to express this list slicing?

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
a_list=("",)*10
(a,b,c1,c2,c3,d 1,d2,d3,d4,d5)= a_list
alist=(a,)
blist=(b,)
clist=(c1,c2,c3 )
dlist=(d2,d3,d4 ,d5)

That obviously work but do I *really* have to do that?

BTW: I know you can do:
alist=a_list[0]
blist=a_list[1]
clist=a_list[2:5]
dlist=a_list[5:]

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.

Thanks,

Nov 30 '06
18 1333
Paul McGuire wrote:
"Paul McGuire" <pt***@austin.r r._bogus_.comwr ote in message
news:Mm******** **********@torn ado.texas.rr.co m...
"John Henry" <jo**********@h otmail.comwrote in message
news:11******** *************@7 9g2000cws.googl egroups.com...
snip

Grrrr... that's what I get for not keeping editor and interpreter windows in
sync. My post was referencing vars I had defined in the interpreter, but
which the function had no clue of. !!! Here's a working version.

-- Paul
def splitUp(src,len s):
ret = []
cur = 0
for length in lens:
if length is not None:
ret.append( src[cur:cur+length] )
cur += length
else:
ret.append( src[cur:] )
return ret

origlist = list("ABCDEFGHI J")
alist, blist, clist, dlist = splitUp( origlist, (1,1,3,None) )
print alist, blist, clist, dlist

Nice.

While we are at it, why not:

class splitUp(object) :
def __init__(self,s rc):
self._src=list( src)
def slice(self, lens):
ret = []
cur = 0
for length in lens:
if length is not None:
ret.append( self._src[cur:cur+length] )
cur += length
else:
ret.append( self._src[cur:] )
return ret

alist, blist, clist, dlist = splitUp("ABCDEF GHIJ").slice((1 ,1,3,None))
print alist, blist, clist, dlist

Now, that's readable!

Nov 30 '06 #11

John Henry wrote:
Paul McGuire wrote:
"Paul McGuire" <pt***@austin.r r._bogus_.comwr ote in message
news:Mm******** **********@torn ado.texas.rr.co m...
"John Henry" <jo**********@h otmail.comwrote in message
news:11******** *************@7 9g2000cws.googl egroups.com...
snip

Grrrr... that's what I get for not keeping editor and interpreter windows in
sync. My post was referencing vars I had defined in the interpreter, but
which the function had no clue of. !!! Here's a working version.

-- Paul
def splitUp(src,len s):
ret = []
cur = 0
for length in lens:
if length is not None:
ret.append( src[cur:cur+length] )
cur += length
else:
ret.append( src[cur:] )
return ret

origlist = list("ABCDEFGHI J")
alist, blist, clist, dlist = splitUp( origlist, (1,1,3,None) )
print alist, blist, clist, dlist


Nice.

While we are at it, why not:

class splitUp(object) :
def __init__(self,s rc):
self._src=list( src)
def slice(self, lens):
ret = []
cur = 0
for length in lens:
if length is not None:
ret.append( self._src[cur:cur+length] )
cur += length
else:
ret.append( self._src[cur:] )
return ret

alist, blist, clist, dlist = splitUp("ABCDEF GHIJ").slice((1 ,1,3,None))
print alist, blist, clist, dlist

Now, that's readable!
Further, if splitUp is a sub-class of string, then I can do:

alist, blist, clist, dlist = "ABCDEFGHIJ".sl ice((1,1,3,None ))

Now, can I override the slice operator?

Nov 30 '06 #12
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
a_list=("",)*10
(a,b,c1,c2,c3,d 1,d2,d3,d4,d5)= a_list
alist=(a,)
blist=(b,)
clist=(c1,c2,c3 )
dlist=(d2,d3,d4 ,d5)

That obviously work but do I *really* have to do that?

BTW: I know you can do:
alist=a_list[0]
blist=a_list[1]
clist=a_list[2:5]
dlist=a_list[5:]

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.

Thanks,
I had a little bit of fun while writing this:

itemList = (a,b,c1,c2,c3,d 1,d2,d3,d4,d5) and
itemList2 = (a1,a2,a3,b,c,d 1,d2,d3,d4,d5) the next time.

def getSlices(aCoun t, bCount, cCount, dCount, items):
a,b,c,d = (items[0:aCount],
items[aCount:aCount+b Count],
items[aCount+bCount:a Count+bCount+cC ount],
item[aCount+bCount+c Count:aCount+bC ount+cCount+dCo unt])
return list(a),list(b) ,list(c),list(d )
>>>a,b,c,d = getSlices(1,1,3 ,5,itemList)
print a,b,c,d
['a'] ['b'] ['c1', 'c2', 'c3'] ['d1', 'd2', 'd3', 'd4', 'd5']
>>>a,b,c,d = getSlices(3,1,1 ,0,itemList2)
print a,b,c,d
['a1', 'a2', 'a3'] ['b'] ['c'] []

%-)

Thomas
Nov 30 '06 #13

John Henry wrote:
>
Further, if splitUp is a sub-class of string, then I can do:

alist, blist, clist, dlist = "ABCDEFGHIJ".sl ice((1,1,3,None ))

Now, can I override the slice operator?
Maybe like:

alist, blist, clist, dlist = newStr("ABCDEFG HIJ")[1,1,3,None]

where newStr is a sub-class of str, with a __repr__ that takes a
variable list of arguments?

(No clue how to code that yet, still pretty new to this)

Maybe they should make this a standard slicing feature....

Nov 30 '06 #14

Thomas Ploch wrote:
<snip>
>
I had a little bit of fun while writing this:

itemList = (a,b,c1,c2,c3,d 1,d2,d3,d4,d5) and
itemList2 = (a1,a2,a3,b,c,d 1,d2,d3,d4,d5) the next time.
Huh? What's a,b,....d5?
def getSlices(aCoun t, bCount, cCount, dCount, items):
a,b,c,d = (items[0:aCount],
items[aCount:aCount+b Count],
items[aCount+bCount:a Count+bCount+cC ount],
item[aCount+bCount+c Count:aCount+bC ount+cCount+dCo unt])
You meant "items" here, right?
return list(a),list(b) ,list(c),list(d )
>>a,b,c,d = getSlices(1,1,3 ,5,itemList)
print a,b,c,d
['a'] ['b'] ['c1', 'c2', 'c3'] ['d1', 'd2', 'd3', 'd4', 'd5']
>>a,b,c,d = getSlices(3,1,1 ,0,itemList2)
print a,b,c,d
['a1', 'a2', 'a3'] ['b'] ['c'] []

%-)

Thomas
Nov 30 '06 #15
John Henry schrieb:
Thomas Ploch wrote:
<snip>
>I had a little bit of fun while writing this:

itemList = (a,b,c1,c2,c3,d 1,d2,d3,d4,d5) and
itemList2 = (a1,a2,a3,b,c,d 1,d2,d3,d4,d5) the next time.

Huh? What's a,b,....d5?
John Henry schrieb:
Thomas Ploch wrote:
<snip>
>I had a little bit of fun while writing this:

itemList = (a,b,c1,c2,c3,d 1,d2,d3,d4,d5) and
itemList2 = (a1,a2,a3,b,c,d 1,d2,d3,d4,d5) the next time.
Huh? What's a,b,....d5?
Can be any object, as you had in your example in your mail:
>>>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
a_list=("",)* 10
(a,b,c1,c2,c3 ,d1,d2,d3,d4,d5 )=a_list
alist=(a,)
blist=(b,)
clist=(c1,c2, c3)
dlist=(d2,d3, d4,d5)
>def getSlices(aCoun t, bCount, cCount, dCount, items):
a,b,c,d = (items[0:aCount],
items[aCount:aCount+b Count],
items[aCount+bCount:a Count+bCount+cC ount],
item[aCount+bCount+c Count:aCount+bC ount+cCount+dCo unt])

You meant "items" here, right?
> return list(a),list(b) ,list(c),list(d )
>>>>a,b,c,d = getSlices(1,1,3 ,5,itemList)
print a,b,c,d
['a'] ['b'] ['c1', 'c2', 'c3'] ['d1', 'd2', 'd3', 'd4', 'd5']
>>>>a,b,c,d = getSlices(3,1,1 ,0,itemList2)
print a,b,c,d
['a1', 'a2', 'a3'] ['b'] ['c'] []

%-)

Thomas
Nov 30 '06 #16

Thomas Ploch wrote:
>
John Henry schrieb:
Thomas Ploch wrote:
<snip>
I had a little bit of fun while writing this:

itemList = (a,b,c1,c2,c3,d 1,d2,d3,d4,d5) and
itemList2 = (a1,a2,a3,b,c,d 1,d2,d3,d4,d5) the next time.

>
Huh? What's a,b,....d5?
>

Can be any object, as you had in your example in your mail:
Oh, sorry.

Nov 30 '06 #17
"John Henry" <jo**********@h otmail.comwrote in message
news:11******** **************@ j72g2000cwa.goo glegroups.com.. .
>
John Henry wrote:
>>
Further, if splitUp is a sub-class of string, then I can do:

alist, blist, clist, dlist = "ABCDEFGHIJ".sl ice((1,1,3,None ))

Now, can I override the slice operator?

Maybe like:

alist, blist, clist, dlist = newStr("ABCDEFG HIJ")[1,1,3,None]
No need to contort string, just expand on your earlier idea. I changed your
class name to SplitUp to more more conventional (class names are usually
capitalized), and changed slice to __call__. Then I changed the lens arg to
*lens - note the difference in the calling format. Pretty close to what you
have above. Also, reconsider whether you want the __init__ function
list-ifying the input src - let the caller decide what to send in.

-- Paul

class SplitUp(object) :
def __init__(self,s rc):
self._src=list( src)
def __call__(self, *lens):
ret = []
cur = 0
for length in lens:
if length is not None:
ret.append( self._src[cur:cur+length] )
cur += length
else:
ret.append( self._src[cur:] )
return ret

alist, blist, clist, dlist = SplitUp("ABCDEF GHIJ")(1,1,3,No ne)
print alist, blist, clist, dlist

Prints:
['A'] ['B'] ['C', 'D', 'E'] ['F', 'G', 'H', 'I', 'J']
Nov 30 '06 #18
Paul McGuire wrote:
"John Henry" <jo**********@h otmail.comwrote in message
news:11******** **************@ j72g2000cwa.goo glegroups.com.. .

John Henry wrote:
>
Further, if splitUp is a sub-class of string, then I can do:

alist, blist, clist, dlist = "ABCDEFGHIJ".sl ice((1,1,3,None ))

Now, can I override the slice operator?
Maybe like:

alist, blist, clist, dlist = newStr("ABCDEFG HIJ")[1,1,3,None]

No need to contort string, just expand on your earlier idea. I changed your
class name to SplitUp to more more conventional (class names are usually
capitalized), and changed slice to __call__. Then I changed the lens arg to
*lens - note the difference in the calling format. Pretty close to what you
have above. Also, reconsider whether you want the __init__ function
list-ifying the input src - let the caller decide what to send in.
In fact, should be possible to make that any object the caller want to
send in...
-- Paul

class SplitUp(object) :
def __init__(self,s rc):
self._src=list( src)
def __call__(self, *lens):
ret = []
cur = 0
for length in lens:
if length is not None:
ret.append( self._src[cur:cur+length] )
cur += length
else:
ret.append( self._src[cur:] )
return ret

alist, blist, clist, dlist = SplitUp("ABCDEF GHIJ")(1,1,3,No ne)
print alist, blist, clist, dlist

Prints:
['A'] ['B'] ['C', 'D', 'E'] ['F', 'G', 'H', 'I', 'J']
Thanks for the help,

Nov 30 '06 #19

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

73
8143
by: RobertMaas | last post by:
After many years of using LISP, I'm taking a class in Java and finding the two roughly comparable in some ways and very different in other ways. Each has a decent size library of useful utilities as a standard portable part of the core language, the LISP package, and the java.lang package, respectively. Both have big integers, although only LISP has rationals as far as I can tell. Because CL supports keyword arguments, it has a wider range...
19
2623
by: David Abrahams | last post by:
Can anyone explain the logic behind the behavior of list slicing with negative strides? For example: >>> print range(10) I found this result very surprising, and would just like to see the rules written down somewhere. Thanks,
12
7039
by: Steven Bethard | last post by:
So I need to do something like: for i in range(len(l)): for j in range(i+1, len(l)): # do something with (l, l) where I get all pairs of items in a list (where I'm thinking of pairs as sets, not tuples, so order doesn't matter). There isn't really anything wrong with the solution here, but since Python's for-each construction is so nice, I usually try to avoid range(len(..)) type
2
1321
by: Philippe C. Martin | last post by:
Hi, I have the following question: l = l #returns l #return 'FGHI' a = l + 'J' #a becomes 'FGHIJ'
9
1723
by: ogerchikov | last post by:
I have 2 classes, A, B and B is a child of A. and I have a function which processes a list of A. void func(list<A> alist) { // processing list of A } The problem is func() won't able to handle a list of B even B is a child of A.
65
4361
by: Steven Watanabe | last post by:
I know that the standard idioms for clearing a list are: (1) mylist = (2) del mylist I guess I'm not in the "slicing frame of mind", as someone put it, but can someone explain what the difference is between these and: (3) mylist =
77
17103
by: Ville Vainio | last post by:
I tried to clear a list today (which I do rather rarely, considering that just doing l = works most of the time) and was shocked, SHOCKED to notice that there is no clear() method. Dicts have it, sets have it, why do lists have to be second class citizens?
19
2925
by: George Sakkis | last post by:
It would be useful if list.sort() accepted two more optional parameters, start and stop, so that you can sort a slice in place. In other words, x = range(1000000) x.sort(start=3, stop=-1) would be equivalent to x = sorted(x)
6
7501
by: Steven D'Aprano | last post by:
If I want to iterate over part of the list, the normal Python idiom is to do something like this: alist = range(50) # first item is special x = alist # iterate over the rest of the list for item in alist x = item
0
10162
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9981
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10687
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9886
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
8253
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7424
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
6112
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4941
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3541
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.