Re: joining strings question
- From: baku <grflanagan@xxxxxxxxx>
- Date: Fri, 29 Feb 2008 08:18:54 -0800 (PST)
On Feb 29, 4:09 pm, patrick.wa...@xxxxxxxxx wrote:
Hi all,
I have some data with some categories, titles, subtitles, and a link
to their pdf and I need to join the title and the subtitle for every
file and divide them into their separate groups.
So the data comes in like this:
data = ['RULES', 'title','subtitle','pdf',
'title1','subtitle1','pdf1','NOTICES','title2','subtitle2','pdf','title3','subtitle3','pdf']
What I'd like to see is this:
[RULES', 'title subtitle','pdf', 'title1 subtitle1','pdf1'],
['NOTICES','title2 subtitle2','pdf','title3 subtitle3','pdf'], etc...
For any kind of data partitioning, you should always keep
`itertools.groupby` in mind as a possible solution:
[code]
import itertools as it
data = ['RULES', 'title','subtitle','pdf',
'title1','subtitle1','pdf1',
'NOTICES','title2','subtitle2','pdf',
'title3','subtitle3','pdf']
def partition(s):
return s == s.upper()
#first method
newdata = []
for k,g in it.groupby(data, partition):
if k:
newdata.append(list(g))
else:
newdata[-1].extend(list(g))
for item in newdata:
print item
#second method
keys = []
vals = []
for k,g in it.groupby(data, partition):
if k:
keys.append(list(g)[0])
else:
vals.append(list(g))
newdata = dict(zip(keys, vals))
print newdata
[/code]
[output]
['RULES', 'title', 'subtitle', 'pdf', 'title1', 'subtitle1', 'pdf1']
['NOTICES', 'title2', 'subtitle2', 'pdf', 'title3', 'subtitle3',
'pdf']
{'RULES': ['title', 'subtitle', 'pdf', 'title1', 'subtitle1', 'pdf1'],
'NOTICES'
: ['title2', 'subtitle2', 'pdf', 'title3', 'subtitle3', 'pdf']}
[/output]
HTH
Gerard
.
- Follow-Ups:
- Re: joining strings question
- From: I V
- Re: joining strings question
- References:
- joining strings question
- From: patrick . waldo
- joining strings question
- Prev by Date: Re: Python's BNF
- Next by Date: Re: Run wxPython app remotely under XWindows
- Previous by thread: Re: joining strings question
- Next by thread: Re: joining strings question
- Index(es):