473,699 Members | 3,134 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

list comprehension for splitting strings into pairs

Here's what I'm doing:
lst = ['1', '1:2', '3', '-1:4']
splits = []
for s in lst: .... pair = s.split(':')
.... if len(pair) != 2:
.... pair.append(Non e)
.... splits.append(p air)
.... splits

[['1', None], ['1', '2'], ['3', None], ['-1', '4']]

Basically, I want to split each string into two items, substituting
None when no second item is specified in the string. (As you can see,
in my strings, the items are delimited by ':').

It seems like a simple enough operation that I should be able to write
a list comprehension for it, but I can't figure out how... Any
suggestions?

Steve
--
You can wordify anything if you just verb it.
- Bucky Katt, Get Fuzzy
Jul 18 '05 #1
5 5353
"Steven Bethard" <st************ @gmail.com> wrote in message
news:ma******** *************** *************** @python.org...
Here's what I'm doing:
lst = ['1', '1:2', '3', '-1:4']
splits = []
for s in lst: ... pair = s.split(':')
... if len(pair) != 2:
... pair.append(Non e)
... splits.append(p air)
... splits [['1', None], ['1', '2'], ['3', None], ['-1', '4']]

Basically, I want to split each string into two items, substituting
None when no second item is specified in the string. (As you can see,
in my strings, the items are delimited by ':').

It seems like a simple enough operation that I should be able to write
a list comprehension for it, but I can't figure out how... Any
suggestions?


How's this?
lst = ['1', '1:2', '3', '-1:4']
splits = [':' in item and item.split(':', 1) or [item, None] \ for item in lst] splits

[['1', None], ['1', '2'], ['3', None], ['-1', '4']]

This approach is cute, but lacks any error-checking, so you can only use it
if you are fairly sure your "lst" will contain strings in the proper format.

--
I don't actually read my hotmail account, but you can replace hotmail with
excite if you really want to reach me.
Jul 18 '05 #2
On Tue, 12 Oct 2004 16:11:45 -0600, Steven Bethard
<st************ @gmail.com> wrote:
Here's what I'm doing:
lst = ['1', '1:2', '3', '-1:4']
splits = []
for s in lst:... pair = s.split(':')
... if len(pair) != 2:
... pair.append(Non e)
... splits.append(p air)
... splits[['1', None], ['1', '2'], ['3', None], ['-1', '4']]

Basically, I want to split each string into two items, substituting
None when no second item is specified in the string. (As you can see,
in my strings, the items are delimited by ':').

It seems like a simple enough operation that I should be able to write
a list comprehension for it, but I can't figure out how... Any
suggestions?

Steve


Here's a pretty nasty approach:
lst = ['1', '1:2', '3', '-1:4']
splits = [(e.split(':') + [None])[:2] for e in lst]
splits

[['1', None], ['1', '2'], ['3', None], ['-1', '4']]
--

Bob Follek
bo*@codeblitz.c om
Jul 18 '05 #3
Russell Blau <russblau <at> hotmail.com> writes:
lst = ['1', '1:2', '3', '-1:4']
splits = [':' in item and item.split(':', 1) or [item, None] for item in lst] splits [['1', None], ['1', '2'], ['3', None], ['-1', '4']]


Oooh. Pretty. =)

What if I want to convert my splits list to:

[[1, None], [1, 2], [3, None], [-1, 4]]

where I actually call int on each of the non-None items? Obviously I could
extend your example to:
lst = ['1', '1:2', '3', '-1:4']
splits = [':' in item and [int(x) for x in item.split(':', 1)] .... or [int(item), None]
.... for item in lst] splits [[1, None], [1, 2], [3, None], [-1, 4]]

But that's getting to be a bit more work than looks good to me in a list
comprehension. I thought about doing it in two steps:
splits = [':' in item and item.split(':', 1) or [item, None] .... for item in lst] splits = [[int(i), p is not None and int(p) or p] .... for i, p in splits] splits

[[1, None], [1, 2], [3, None], [-1, 4]]

This looks decent to me, but if you see a better way, I'd love to hear about
it. =)

Thanks again!

Steve
Jul 18 '05 #4
Steven Bethard <steven.betha rd <at> gmail.com> writes:
splits = [':' in item and item.split(':', 1) or [item, None] ... for item in lst] splits = [[int(i), p is not None and int(p) or p] ... for i, p in splits] splits

[[1, None], [1, 2], [3, None], [-1, 4]]


So I realized that this doesn't quite work if the second item in a split is 0 -
- you'll end up with None instead of 0.

Steve

Jul 18 '05 #5
Steven Bethard <st************ @gmail.com> wrote:
lst = ['1', '1:2', '3', '-1:4']
splits = []
for s in lst: .... pair = s.split(':')
.... if len(pair) != 2:
.... pair.append(Non e)
.... splits.append(p air)
.... splits [['1', None], ['1', '2'], ['3', None], ['-1', '4']] Basically, I want to split each string into two items, substituting
None when no second item is specified in the string. (As you can see,
in my strings, the items are delimited by ':').


Ah!
lst = ['1', '1:2', '3', '-1:4']
[ (x.split(':') + [None])[:2] for x in lst] [['1', None], ['1', '2'], ['3', None], ['-1', '4']]

Handles both single-element and more-than-two-element strings. Doesn't
crash on empty strings, but the result probably isn't useful:
[ (x.split(':') + [None])[:2] for x in ['1', '1:2', '3', '-1:4', '']] [['1', None], ['1', '2'], ['3', None], ['-1', '4'], ['', None]]

You might also enjoy this variation
[ (map(int, x.split(':')) + [None])[:2] for x in lst]

[[1, None], [1, 2], [3, None], [-1, 4]]

Since I saw you mention wanting that later, I think. Didn't see any
replies quite the same as this (but I didn't troll through the rest of
the spool looking for possible unthreaded replies).

--
One discharges fancy homunculi from one's scheme
by organizing armies of idiots to do the work. -- Dennett
Jul 18 '05 #6

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

Similar topics

11
2486
by: Guy Robinson | last post by:
Hello, Trying to change a string(x,y values) such as : s = "114320,69808 114272,69920 113568,71600 113328,72272" into (x,-y): out = "114320,-69808 114272,-69920 113568,-71600 113328,-72272"
6
1493
by: Eric | last post by:
Pythonistas, I seem at a loss for a List Comprehension syntax that will do what I want. I have a list of string position spans: >>> breaks the first pair representing: someString
7
2269
by: Chris P. | last post by:
Hi. I've made a program that logs onto a telnet server, enters a command, and then creates a list of useful information out of the information that is dumped to the screen as a result of the command. Here's a generic version of the code in question: ##### # Prior code opens telnet connection "tn" and logs in. tn.read_until('> ') tn.write('THE COMMAND IS HERE\n')
34
3286
by: jblazi | last post by:
Let us assume I have a list like and would like to transoform it into the string '{1,2},{7,8},{12,13}' Which is the simplest way of achiebing this? (The list is in fact much longer and I may have to cut the resulting strings into chunks of 100 or
6
1997
by: C Gillespie | last post by:
Dear All, If I have a list, say x= What's the best way of converting it into this: , , ], i.e. splitting it into pairs. Many thanks
21
2373
by: Timothy Babytch | last post by:
Hi all. I have a list that looks like , , ] I try to make it flat one: How can I archieve such an effect with list comprehension? Two cycles did the job, but that way did not look pythonic.. I tried print
17
1840
by: Girish Sahani | last post by:
I have a list of strings all of length k. For every pair of k length strings which have k-1 characters in common, i want to generate a k+1 length string(the k-1 common characters + 2 not common characters). e.g i want to join 'abcd' with bcde' to get 'abcde' but i dont want to join 'abcd' with 'cdef' Currently i'm joining every 2 strings, then removing duplicate characters from every joined string and finally removing all those strings...
3
1816
by: Girish Sahani | last post by:
Hi, I am trying to convert a list of pairs (l4) to list l5 by removing those pairs from l4 which are not present in a third list called pairList. The following is a simplified part of the routine i have written. However it does not give the correct output. Please help! Its possible i have made a trivial mistke since i am a newbie. def getl5(): l5 = pairList = ,,,,,,,,]
6
1438
by: rkmr.em | last post by:
Hi I need to process a really huge text file (4GB) and this is what i need to do. It takes for ever to complete this. I read some where that "list comprehension" can fast up things. Can you point out how to do it in this case? thanks a lot! f = open('file.txt','r') for line in f:
0
8633
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
9055
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
8947
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
7787
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...
0
5891
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
4392
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
4642
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2366
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2016
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.