Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #9449
| Date | 2011-07-13 22:58 +0100 |
|---|---|
| From | MRAB <python@mrabarnett.plus.com> |
| Subject | Re: I don't know list, I not good at list. |
| References | <77AE044B1BF3944FAE2435F395F11B4B018599C6@clt-exmb02.bbtnet.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.1009.1310594335.1164.python-list@python.org> (permalink) |
> I've been beating my head against the desk trying to figure out a
> method to accomplish this:
>
> Take a list (this example is 5 items, It could be 150 or more - i.e.
> it's variable length depending on the city/local calling zones)
>
> The first 6 digits of phone numbers(NPA/NXX) in a local calling area.
> I want to concatenate the last digit for insertion into a call
> routing pattern.
>
> I tried this and failed miserably:
>
> list1=['252205','252246','252206','252247','252248']
> for item in list1:
> try:
> item1=list1[0]
> item2=list1[1]
> if item1[0:5] == item2[0:5]:
> print item1[0:5] + '[' + item1[5:6] +
item2[5:6] + ']'
> list1.pop(0)
> else:
> print item1
> list1.pop(0)
> except:
> try:
> print item1
> list1.pop(0)
> except:
> pass
>
> #-----------------------------------------------------------------
> My intent is to have the end data come out (from the example list
> above) in the format of
> 25220[56]
> 25224[678]
>
> I tried putting together a variable inserted into a regular
> expression, and it doesn't seem to like:
> Item1=list1[0]
> Itemreg = re.compile(Item1[0:5])
> For stuff in itemreg.list1:
> #do something
>
> Can somebody throw me a bone, code example or module to read on
> python.org? I'm a n00b, so I'm still trying to understand functions
> and classes.
>
> I thought the experts on this list might take pity on my pathetic
> code skillz!
>
defaultdict comes in handy:
>>> list1 = ['252205','252246','252206','252247','252248']
>>> from collections import defaultdict
>>> d = defaultdict(set)
>>> for item in list1:
d[item[ : 5]].add(item[5 : ])
>>> d
defaultdict(<class 'set'>, {'25224': {'8', '7', '6'}, '25220': {'5', '6'}})
>>> for k, v in d.items():
print(k + "[" + "".join(v) + "]")
25224[876]
25220[56]
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: I don't know list, I not good at list. MRAB <python@mrabarnett.plus.com> - 2011-07-13 22:58 +0100
csiph-web