473,796 Members | 2,703 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Splitting a list

string.split() is very useful, but what if I want to split a list of integers on some element value?

e.g. :
l = [1,2,3,-1,4,5,-1,8,9]
l.split(-1)
[[1,2,3],[4,5],[8,9]]
Here's my hideous first pass :
[[int(z) for z in x.split(',') if z] for x in ','.join([str(a) for a in l]).split('-1')]
[[1, 2, 3], [4, 5], [8, 9]]


When I see code like that I just know I've missed something obvious....

Jul 18 '05 #1
4 1905
def indices(x,y):
if y in x:
i = x.index(y)
j = i+1
return [i]+[z+j for z in indices(x[j:],y)]
return []

def listSplit(x,y):
z = [-1] + indices(x,y) + [len(x)]
return [x[z[i]+1:z[i+1]] for i in range(len(z)-1)]
"Ian Sparks" <Ia********@etr ials.com> wrote in message
news:ma******** *************** *************** @python.org...
string.split() is very useful, but what if I want to split a list of integers on
some element value?

e.g. :
l = [1,2,3,-1,4,5,-1,8,9]
l.split(-1)
[[1,2,3],[4,5],[8,9]]
Here's my hideous first pass :
[[int(z) for z in x.split(',') if z] for x in ','.join([str(a) for a in l]).split('-1')] [[1, 2, 3], [4, 5], [8, 9]]


When I see code like that I just know I've missed something obvious....


Jul 18 '05 #2
On Tue, 31 Aug 2004 09:54:17 -0400, "Ian Sparks"
<Ia********@etr ials.com> wrote:
string.split () is very useful, but what if I want to split a list of integers on some element value?


Here are a few early-morning attempts :-)

def lsplit(L,sep):
try:
i = L.index(sep)
return [L[:i]] + lsplit(L[i+1:],sep)
except ValueError:
return [L]

def lsplit2(L,sep):
i = 0
res = []
while True:
try:
j = L.index(sep,i)
res.append(L[i:j])
i = j+1
except ValueError:
res.append(L[i:])
break
return res

def lsplit3(L,sep):
i = 0
while True:
try:
j = L.index(sep,i)
yield L[i:j]
i = j+1
except ValueError:
yield L[i:]
break
HTH
Andrea
Jul 18 '05 #3
Ian Sparks <Ia********@etr ials.com> wrote:
string.split() is very useful, but what if I want to split a list of integers on some element value?

e.g. :
l = [1,2,3,-1,4,5,-1,8,9]
l.split(-1)
[[1,2,3],[4,5],[8,9]]


reduce (lambda a, i: i == elem and (a + [[]]) or (a[:-1] + [a[-1]+[i]]),
l, [[]])

martin
Jul 18 '05 #4
Ian Sparks <Ia********@etr ials.com> wrote:
string.split() is very useful, but what if I want to split a list of integers on some element value?
e.g. :
l = [1,2,3,-1,4,5,-1,8,9]
l.split(-1)
[[1,2,3],[4,5],[8,9]]
Here's my hideous first pass :
[[int(z) for z in x.split(',') if z] for x in ','.join([str(a) for a in l]).split('-1')] [[1, 2, 3], [4, 5], [8, 9]]
When I see code like that I just know I've missed something obvious....


I think a simple generator might serve you well:

def isplit(seq, separator):
result = []
for item in seq:
if item == separator:
yield result
result = []
else:
result.append(i tem)
yield result

example use:
list(isplit([1,2,3,-1,4,5,-1,8,9], -1))

[[1, 2, 3], [4, 5], [8, 9]]

Note that, the way isplit is coded, seq can be any iterable, not just a
list. You may not need this little extra generality, but it can't
hurt...
Alex
Jul 18 '05 #5

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

Similar topics

13
6803
by: Rajarshi Guha | last post by:
Hi, is there an efficient (pythonic) way in which I could split a list into say 5 groups? By split I mean the the first x members would be one group, the next x members another group and so on 5 times. (Obviously x = lengthof list/5) I have done this by a simple for loop and using indexes into the list. But it does'nt seemm very elegant Thanks,
18
2076
by: robsom | last post by:
Hi, I have a problem with a small python program I'm trying to write and I hope somebody may help me. I'm working on tables of this kind: CGA 1988 06 21 13 48 G500-050 D 509.62 J.. R1 1993 01 28 00 00 880006 CGA 1988 06 21 14 04 G500-051 D 550.62 J.. R1 1993 01 28 00 00 880007 I have to read each line of the table and put it into comma-separated lists like these for later manipulation: ...
6
1930
by: qwweeeit | last post by:
Splitting with RE has (for me!) misterious behaviour! I want to get the words from this string: s= 'This+(that)= a.string!!!' in a list like that considering "a.string" as a word. Python 2.3.4 (#2, Aug 19 2004, 15:49:40) on linux2
3
2539
by: William Ahern | last post by:
I'm looking for resources on splitting and merging XML trees. Specifically, on methods to pare large XML documents into smaller documents which can be merged later. Off of the top of my head, I can envision unions of node sets, and unions of node text. But I know there's much more to the subject than that, if not more alternatives than greater technical detail. TIA,
7
2236
by: qwweeeit | last post by:
Hi all, I am writing a script to visualize (and print) the web references hidden in the html files as: '<a href="web reference"> underlined reference</a>' Optimizing my code, I found that an essential step is: splitting on a word (in this case 'href'). I am asking if there is some alternative (more pythonic...): # SplitMultichar.py
9
1872
by: amitavabardhan | last post by:
How Can I extract multiple tiff images into single images through asp programming? Is there any free dll's that I can use in ASP to split multiple tiffs into single tiffs? Any suggestion regarding this issue will be highly appreciated.....
4
2710
by: guitarromantic | last post by:
Hey everyone. Following advice found online, I figured out a basic way of splitting a long article into several pages, by exploding out from a <!--pagebreak--> code in my $content field. http://www.scenepointblank.com/matt/dev/features/index.php?id=1&page=1 Sample above. The next/previous links were built with simple values:
1
2173
by: sadiewms | last post by:
Hello! I have a flat file that I'm trying to get into a relational Access 2003 DB. One of the fields in the flat file has a list of names separated by ";". I'd like to loop through them and create new records for each in a table relational DB. ( name1; name2; name3; name4) I'm getting stuck on splitting the string. Because there may be up to 6 names in the original field I can't use the Left(), Mid() functions. I've also tried...
4
5377
by: Michael Yanowitz | last post by:
Hello: For some reason I can't figure out how to split a 4-byte (for instance) float number (such as 3.14159265359) into its 4-bytes so I can send it via a socket to another computer. For integers, it is easy, I can get the 4 bytes by anding like: byte1 = int_val & 0x000000FF byte2 = int_val & 0x0000FF00 byte3 = int_val & 0x00FF0000
2
3273
by: shadow_ | last post by:
Hi i m new at C and trying to write a parser and a string class. Basicly program will read data from file and splits it into lines then lines to words. i used strtok function for splitting data to lines it worked quite well but srttok isnot working for multiple blank or commas. Can strtok do this kind of splitting if it cant what should i use . Unal
0
10239
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
10190
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
10019
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
9057
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
7555
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
6796
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
5447
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...
0
5579
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4122
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

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.