[Tutor] how to unique the string

lina lina.lastname at gmail.com
Mon Oct 24 10:05:11 CEST 2011


On Mon, Oct 24, 2011 at 3:24 PM, Peter Otten <__peter__ at web.de> wrote:
> lina wrote:
>
>> But I am getting confused later:
>>
>> def translate_process(dictionary,tobetranslatedfile):
>>     results=[]
>>     unique={}
>>     for line in open(tobetranslatedfile,"r"):
>>         tobetranslatedparts=line.strip().split()
>>         results.append(dictionary[tobetranslatedparts[2]])
>
>>         unique=Counter(results)
>>         with open(base+OUTPUTFILEEXT,"w") as f:
>>             for residue, numbers in unique.items():
>>                 print(residue,numbers,file=f)
>
> As Dave says, the above four lines should run only once, outside the for-
> loop.
>
> Here's a way to avoid the intermediate results list. As a bonus I'm removing
> access to the `base` global variable:
>
> def change_ext(name, new_ext):
>    """
>    >>> change_ext("/deep/blue.eyes", ".c")
>    '/deep/blue.c'
>    """
>    return os.path.splitext(name)[0] + new_ext
>
> def translate_process(dictionary, tobetranslatedfile):
>    with open(tobetranslatedfile, "r") as f:
>        results = (dictionary[line.split()[2]] for line in f)
>        unique = Counter(results)
>
>    with open(change_ext(tobetranslatedfile, OUTPUTFILEEXT), "w") as out:
>        for residue, numbers in unique.items():
>            print(residue, numbers, file=out)

Now work as expected. concise than before.

Thanks,
>
>
>> it still the same in the OUTPUTFILE as before,
>>
>>  $ more atom-pair_6.txt
>> {'26SER': 2, '16LYS': 1, '83ILE': 2, '70LYS': 6, '55HIS': 5}
>
> Unlikely. Verify that you are running the correct script and looking into
> the right output file.
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


More information about the Tutor mailing list