TickingClock的个人博客分享 http://blog.sciencenet.cn/u/TickingClock

博文

Rosalind 6 - Dictionaries

已有 4728 次阅读 2017-10-22 08:28 |个人分类:Python Learning|系统分类:科研笔记

Python Village - INI6: Dictionaries


Intro to Python dictionary


Python中除了lists和strings存储和处理数据,还有一种变量叫做dictionary,其类似于lists,但存储的对象有所区别,比如我们可以用以下的方法创建一个dictionary:


>>> phones = {'Zoe':'232-43-58', 'Alice':'165-88-56'}
>>> print phones['Zoe']
232-43-58

>>>


可见,'Zoe'就是字典中的index,这里叫做key,然后dictionary就相当于给每个key进行赋值,当你要求输入key时,返回值则是对应于该key的赋值:'Zoe'对应的是'232-43-58',而'Alice'对应的是'165-88-56'。


可以通过直接赋予key新的值来取代旧的值:


>>> phones['Zoe'] = '658-99-55'
>>> print phones
{'Zoe': '658-99-55', 'Alice': '165-88-56'}

>>>


Zoe对应的值从'232-43-58'变为了'658-99-55'。还可以通过直接写入新的key与赋值来进行添加:


>>> phones['Bill'] = '342-18-25'
>>> print phones
{'Bill': '342-18-25', 'Zoe': '658-99-55', 'Alice': '165-88-56'}

>>>


添加了Bill的号码信息。(注意,Bill的信息在第一个,而不是最后一个)


另外,要注意dictionary中会区别大小写:


>>> d = {}
>>> d['key'] = 1
>>> d['Key'] = 2
>>> d['KEY'] = 3
>>> print d
{'KEY': 3, 'Key': 2, 'key': 1}

>>>


如果需要检查dictionary是否存在某个key,可以使用key in d的语法:


>>> if 'Peter' in phones:
...        print "We know Peter's phone"
...      else:
...        print "We don't know Peter's phone"
...
We don't know Peter's phone

>>>


如果想删除dictionary中的某个key,可以使用del命令:


>>> phones = {'Zoe':'232-43-58', 'Alice':'165-88-56'}
>>> del phones['Zoe']
>>> print phones
{'Alice': '165-88-56'}

>>>


Problem


Given: A string s of length at most 10000 letters.


Return: The number of occurrences of each word in s, where words are separated by spaces. Words are case-sensitive, and the lines in the output can be in any order.


Sample Dataset


We tried list and we tried dicts also we tried Zen


Sample Output


and 1
We 1
tried 3
dicts 1
list 1
we 2
also 1

Zen 1


Solution


>>> s = 'We tried list and we tried dicts also we tried Zen'.split()
>>> d = {}
>>> for i in s:
...        d[i] = s.count(i)
...
>>> for i in d:
...        print i, d[i]
...
and 1
We 1
tried 3
dicts 1
Zen 1
list 1
we 2
also 1

>>>


另外,看到有网友leafmoon写的代码,利用的collections中的Counter命令,没有用dictionary:


>>> s = 'We tried list and we tried dicts also we tried Zen'.split()
>>> from collections import Counter
>>> for k,v in Counter(s).items():
...        print k,v
...
and 1
We 1
tried 3
dicts 1
Zen 1
list 1
we 2
also 1

>>>


Over


到这Python Village部分就已经完成了,下面就开始Bioinformatics Stronghold项目了,加油!


Rosalind is a platform for learning bioinformatics and programming through problem solving. Take a tour to get the hang of how Rosalind works.


P.S. 欢迎关注微信公众号:微信号Plant_Frontiers




https://blog.sciencenet.cn/blog-3158122-1081925.html

上一篇:Plant Physiology:类黄酮调控ABA诱导的ROS以控制气孔的开闭
下一篇:Plant Physiology:棉花中长、短绒纤维的转录组研究
收藏 IP: 49.77.176.*| 热度|

0

该博文允许注册用户评论 请点击登录 评论 (0 个评论)

数据加载中...
扫一扫,分享此博文

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-12-29 13:36

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部