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

博文

Rosalind 3 - Strings and Lists

已有 2951 次阅读 2017-10-19 08:31 |个人分类:Python Learning|系统分类:科研笔记|关键词:学者

Python Village - INI3: Strings and Lists


Python除了strings和numbers数据类型,还有更加复杂一点的数据类型,比如说lists。


list的赋值方式是list_name = [item_1, item_2, ..., item_n],比如:


>>> tea_party = ['March Hare', 'Hatter', 'Dormouse', 'Alice']
>>> print tea_party[2]
Dormouse

>>>


注意,在Python中,list内部item计数是从0开始的,因此tea_party[2]对应的item是'Dormouse',而不是'Hatter'。


可以直接赋予list新的值已取代旧的item:


>>> tea_party[1] = 'Cheshire Cat'
>>> print tea_party
['March Hare', 'Cheshire Cat', 'Dormouse', 'Alice']

>>>


第2个item从'Hatter'变成了'Cheshire Cat'。


另外,往已有的list中添加item可以用append()函数:


>>> tea_party.append('Jabberwocky')
>>> print tea_party
['March Hare', 'Cheshire Cat', 'Dormouse', 'Alice', 'Jabberwocky']

>>>


可见tea_party最后新增了一个item,'Jabberwocky’。


如果想获取某个list中的某几个元素,可以使用list_name[a:b]函数:


>>> tea_party[1:3]
['Cheshire Cat', 'Dormouse']

>>>


可见list_name[a:b]获取的是从a到b,但不包括b的items。


另外,a或者b一方为空值的话,表示取a到最后一个值或者第一个值到b:


>>> tea_party[:2]
['March Hare', 'Cheshire Cat']
>>> tea_party[3:]
['Alice', 'Jabberwocky']

>>>


此外,也可以使用负数,代表从后往前数:


>>> tea_party[-2:]
['Alice', 'Jabberwocky']

>>>


因为tea_party一共有5个item,因此tea_party[3:]与tea_party[-2:]得到的结果是一样的。


同样,我们可以用这种方法去应用于strings上:


>>> a = 'flimsy'
>>> b = 'miserable'
>>> c = b[0:1] + a[2:]
>>> print c
mimsy

>>>


b[0:1]返回的是m,a[2:]返回的是imsy,加起来就是mimsy。


Problem


Given: A string s of length at most 200 letters and four integers a, b, c and d.

Return: The slice of this string from indices a through b and c through d (with space in between), inclusively. In other words, we should include elements s[b] and s[d] in our slice.


Sample Dataset


HumptyDumptysatonawallHumptyDumptyhadagreatfallAlltheKingshorsesandalltheKingsmenCouldntputHumptyDumptyinhisplaceagain.

22 27 97 102


Sample Output


Humpty Dumpty


Solution


这个需要看清楚题目,第一个是输出的值中间有空格,第二个是s[b]与s[d]包括在内:


>>> s = 'HumptyDumptysatonawallHumptyDumptyhadagreatfallAlltheKingshorsesandalltheKingsmenCouldntputHumptyDumptyinhisplaceagain'
>>> print s[22:27+1] + ' ' + s[97:102+1]
Humpty Dumpty
>>>
Over


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://m.sciencenet.cn/blog-3158122-1081477.html

上一篇:Cell:通过基因组编辑为作物改良提供数量性状变异
下一篇:Nature Communications:稗草基因组分析揭示其广泛适应性机制

0

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

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

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

GMT+8, 2024-4-28 08:23

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部