Dumb Stupid Question About List and String

MRAB python at mrabarnett.plus.com
Wed Sep 1 19:22:29 CEST 2010


On 01/09/2010 17:49, Alban Nona wrote:
> Hello Xavier,
>
> Thank you :)
>
> Well what Iam trying to generate is that kind of result:
>
> listn1=['ELM001_DIF', 'ELM001_SPC', 'ELM001_RFL', 'ELM001_SSS',
> 'ELM001_REFR', 'ELM001_ALB', 'ELM001_AMB', 'ELM001_NRM', 'ELM001_MVE',
> 'ELM001_DPF', 'ELM001_SDW', 'ELM001_MAT', 'ELM001_WPP']
>
> listn2 = ['ELM002_DIF', 'ELM002_SPC', 'ELM002_RFL', 'ELM002_SSS',
> 'ELM002_REFR', 'ELM002_ALB', 'ELM002_AMB', 'ELM002_NRM', 'ELM002_MVE',
> 'ELM002_DPF', 'ELM002_SDW', 'ELM002_MAT', 'ELM002_WPP']
>
> etc...
>
> The thing is, the first list will be generated automatically. (so there
> will be unknow versions of ELM00x....)
> that why Im trying to figure out how to genere variable and list in an
> automatic way.
>
> Can you tell me if its not clear please ? :P
> my english still need improvement when Im trying to explain scripting
> things.
>
[snip]
Create a dict in which the key is the "ELEM" part and the value is a
list of those entries which begin with that "ELEM" part.

For example, if the entry is 'ELEM001_DIF' then the key is 'ELEM001',
which is the first 7 characters of entry, or entry[ : 7].

Something like this:

     elem_dict = {}
     for entry in list_of_entries:
         key = entry[ : 7]
         if key in elem_dict:
             elem_dict[key].append(entry)
         else:
             elem_dict[key] = [entry]



More information about the Python-list mailing list