473,833 Members | 2,199 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 #1
18 1320
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,
Nothing in your code actually __is__ a list. they are all tuples...
A list is:
aList = [a,b,c1,c2,c3,d1 ,d2,d3,d4,d5]

Thomas
Nov 30 '06 #2
Well, pardoon me.

Next.

Thomas Ploch wrote:
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,

Nothing in your code actually __is__ a list. they are all tuples...
A list is:
aList = [a,b,c1,c2,c3,d1 ,d2,d3,d4,d5]

Thomas
Nov 30 '06 #3
On 11/30/06, Thomas Ploch <Th**********@g mx.netwrote:
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,

Nothing in your code actually __is__ a list. they are all tuples...
A list is:
aList = [a,b,c1,c2,c3,d1 ,d2,d3,d4,d5]
True but not relevant, really, he should have said "sequence". But
more importantly,
you don't show what you do with alist, blist,clist,dli st. Without
knowing what the end result is, nobody is going to be able to help you
eliminate the middle steps.
Thomas
--
http://mail.python.org/mailman/listinfo/python-list
Nov 30 '06 #4
John Henry wrote:
Can I say something to the effect of:

(a,b,c[0:2],d[0:5])=a_list # Obviously this won't work
Your best bet is probably:

x = [...some list...]
a,b,c,d = x[:1],x[1:2],x[2:5],x[5:]
I am asking this because I have a section of code that contains *lots*
of things like this. It makes the code very unreadable.
Of course, if you're always slicing up lists the same way (say, into
1,1,3,5 element sections) then you could improve readability by writing
a function that takes the list and returns a tuple of the pieces, such
as:

def slice_list(x):
return x[:1],x[1:2],x[2:5],x[5:]

a,b,c,d = slice_list(firs t_list)
e,f,g,h = slice_list(seco nd_list)

-Matt

Nov 30 '06 #5
On 2006-11-30, John Henry <jo**********@h otmail.comwrote :
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?
Please post actual code we can run, rather than text that is
almost, but not quite, entirely unlike Python code.
BTW: I know you can do:
alist=a_list[0]
blist=a_list[1]
Note that alist and blist are not necessarily lists, as you did
not use slice notation.
clist=a_list[2:5]
dlist=a_list[5:]

but I don't see that it's any better.
I think it looks much better, personally.

If you are iterating through that sequence of slices a lot,
consider using a generator that yields the sequence.
>>def parts(items):
... yield items[0:1]
... yield items[1:2]
... yield items[2:5]
... yield items[5:]
>>for seq in parts(range(10) ):
... print seq
[0]
[1]
[2, 3, 4]
[5, 6, 7, 8, 9]

--
Neil Cerutti
I guess there are some operas I can tolerate and Italian isn't one of them.
--Music Lit Essay
Nov 30 '06 #6
On 2006-11-30, Neil Cerutti <ho*****@yahoo. comwrote:
On 2006-11-30, John Henry <jo**********@h otmail.comwrote :
>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=("",)*1 0
(a,b,c1,c2,c3, d1,d2,d3,d4,d5) =a_list
alist=(a,)
blist=(b,)
clist=(c1,c2,c 3)
dlist=(d2,d3,d 4,d5)

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

Please post actual code we can run, rather than text that is
almost, but not quite, entirely unlike Python code.
Ummm... that comment is withdrawn. :-O

--
Neil Cerutti
Nov 30 '06 #7
"John Henry" <jo**********@h otmail.comwrote in message
news:11******** *************@7 9g2000cws.googl egroups.com...
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.
The slicing notation is about the best general solution.

If you are doing this a lot, you should write some sort of "break up the
list function". Here's one that takes a list of list lengths to break the
list into.

-- Paul
def splitUp(src,len s):
ret = []
cur = 0
for var,length in varmap:
if length is not None:
ret.append( a_list[cur:cur+length] )
cur += length
else:
ret.append( a_list[cur:] )
return ret
origlist = list("ABCDEFGHI J")
alist, blist, clist, dlist = splitUp( origlist, (1,1,3,None) )
print alist, blist, clist, dlist

Prints
['A'] ['B'] ['C', 'D', 'E'] ['F', 'G', 'H', 'I', 'J']
Nov 30 '06 #8
"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
Nov 30 '06 #9

md******@gmail. com wrote:
John Henry wrote:
Can I say something to the effect of:

(a,b,c[0:2],d[0:5])=a_list # Obviously this won't work

Your best bet is probably:

x = [...some list...]
a,b,c,d = x[:1],x[1:2],x[2:5],x[5:]
Dude! Why didn't I think of that (tunnel vision).

Thanks,

I am asking this because I have a section of code that contains *lots*
of things like this. It makes the code very unreadable.

Of course, if you're always slicing up lists the same way (say, into
1,1,3,5 element sections) then you could improve readability by writing
a function that takes the list and returns a tuple of the pieces, such
as:

def slice_list(x):
return x[:1],x[1:2],x[2:5],x[5:]

a,b,c,d = slice_list(firs t_list)
e,f,g,h = slice_list(seco nd_list)

-Matt
Nov 30 '06 #10

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

Similar topics

73
8099
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
2612
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
7020
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
1316
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
1716
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
4256
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
17074
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
2915
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
7482
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
9796
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
9642
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
10500
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10543
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9323
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
7753
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
5624
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
4422
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
3078
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.