[Tutor] how to unique the string
Peter Otten
__peter__ at web.de
Sun Oct 23 12:06:05 CEST 2011
lina wrote:
>>> tobetranslatedparts=line.strip().split()
strip() is superfluous here, split() will take care of the stripping:
>>> " alpha \tbeta\n".split()
['alpha', 'beta']
>>> for residue in results:
>>> if residue not in unique:
>>> unique[residue]=1
>>> else:
>>> unique[residue]+=1
There is a dedicated class to help you with that, collections.Counter:
>>> from collections import Counter
>>> results = ["alpha", "beta", "gamma", "alpha"]
>>> unique = Counter(results)
>>> unique
Counter({'alpha': 2, 'beta': 1, 'gamma': 1})
Counter is a subclass of dict, so the stuff you are doing with `unique`
elswhere should continue to work.
> This part I just wish the output in file like:
>
> {'26SER': 2, '16LYS': 1, '83ILE': 2, '70LYS': 6}
>
> as
>
> 26SER 2
> 16LYS 1
> 83ILE 2
> 70LYS 6
You can redirect the output of print() to a file using the `file` keyword
argument:
>>> unique = {'26SER': 2, '16LYS': 1, '83ILE': 2, '70LYS': 6}
>>> with open("tmp.txt", "w") as f:
... for k, v in unique.items():
... print(k, v, file=f)
...
>>>
$ cat tmp.txt
26SER 2
83ILE 2
70LYS 6
16LYS 1
$
More information about the Tutor
mailing list