写在前面
一、列表
定义新的列表:变量名称 = [元素1, 元素2, 元素3, 元素4, ....]
定义空列表:变量名称 = []变量名称 = list()
列表中的元素比较灵活,可以均互不相同:
# 可以发现,下面列表的三个元素均不同bioinformatic = [2023, 'Biomamba',True]print(type(bioinformatic))# 这意味着列表里可以"套"列表,称为嵌套列表## <class 'list'>bioinformatic = [2023, 'Biomamba',True,[2023, 'subBiomamba',True]]print(type(bioinformatic))## <class 'list'>列表中元素的索引有些反人类,第一个元素的索引编号为0,第二个索引编号为1,一次类推,可用list[索引编号的方式取出]
bioinformatic = [2023, 'Biomamba',True]print(bioinformatic[0])## 2023print(bioinformatic[1])## Biomambaprint(bioinformatic[2])## True不仅可以正着数,列表索引还支持倒着数,最后一个元素的索引为-1,倒数第二个的索引为-2,依次类推:
bioinformatic = [2023, 'Biomamba',True]print(bioinformatic[-1])## Trueprint(bioinformatic[-2])## Biomambaprint(bioinformatic[-3])## 2023那么问题来了,嵌套的索引如何取出元素呢:
# 取出subBiomamba这个元素bioinformatic = [2023, 'Biomamba',True,[2023, 'subBiomamba',True]]print(bioinformatic[3][1])# 倒着取:## subBiomambaprint(bioinformatic[-1][-2])## subBiomamba记得索引不要超出范围,否则会报错list index out of range:9.1.4 list中的方法与操作
list.index(元素) 该方法可以根据元素的内容找出元素在列表中对应的下标:
bioinformatic = [2023, 'Biomamba',True,[2023, 'subBiomamba',True]]bioinformatic.index('Biomamba')#返回了`Biomamba`字符所在的正向索引:## 1# 若查找的元素不存在,则会报错:bioinformatic.index('Bioinformatics')ValueError: ‘Bioinformatics’ is not in list
bioinformatic[1] ="我是一个修改后的元素"print(bioinformatic)# 可以看到bioinformatic这个列表中索引1对应的元素已被替换:## [2023, '我是一个修改后的元素', True, [2023, 'subBiomamba', True]]bioinformatic.insert(1,'新插入的元素')print(bioinformatic)# 可以看到元素被插入索引1的位置,后面的元素被依次推后## [2023, '新插入的元素', '我是一个修改后的元素', True, [2023, 'subBiomamba', True]]# 如果像R语言那样输入一个不存在的索引去追加,就会出现如下报错bioinformatic[6] ='我是一个追加的元素'IndexError: list assignment index out of range
# 通过append方法可以做到我们设想的追加功能:bioinformatic.append('我是一个追加的元素')print(bioinformatic)# 只能写入尾部## [2023, '新插入的元素', '我是一个修改后的元素', True, [2023, 'subBiomamba', True], '我是一个追加的元素']list.append的方式只能向尾部添加单个字面量,而list.extend可以直接把其它数据容器中的内容整个取出,依次追加到列表尾部:
new_list = [1,2,3]print(new_list)## [1, 2, 3]bioinformatic.extend(new_list)print(bioinformatic)## [2023, '新插入的元素', '我是一个修改后的元素', True, [2023, 'subBiomamba', True], '我是一个追加的元素', 1, 2, 3]# 方式一# del 列表[下标]print(bioinformatic)## [2023, '新插入的元素', '我是一个修改后的元素', True, [2023, 'subBiomamba', True], '我是一个追加的元素', 1, 2, 3]del bioinformatic[-1]print(bioinformatic)## [2023, '新插入的元素', '我是一个修改后的元素', True, [2023, 'subBiomamba', True], '我是一个追加的元素', 1, 2]# 方式二# 列表.pop(下标)print(bioinformatic)## [2023, '新插入的元素', '我是一个修改后的元素', True, [2023, 'subBiomamba', True], '我是一个追加的元素', 1, 2]bioinformatic.pop(-1)## 2print(bioinformatic)## [2023, '新插入的元素', '我是一个修改后的元素', True, [2023, 'subBiomamba', True], '我是一个追加的元素', 1]# pop方法的实质是从列表中取出对应元素,因此,pop方法可以返回对应的值:print(bioinformatic)## [2023, '新插入的元素', '我是一个修改后的元素', True, [2023, 'subBiomamba', True], '我是一个追加的元素', 1]my_value = bioinformatic.pop(-1)print(my_value)## 1# 方式3 list.remove()new_list = ['num_1','num_2','num_3','num_1','num_4']new_list.remove('num_1')print(new_list)# 可以看出remove方法通过给定内容,在列表中正序检索,删除对应的元素## ['num_2', 'num_3', 'num_1', 'num_4']print(new_list)## ['num_2', 'num_3', 'num_1', 'num_4']new_list.clear()print(new_list)## []new_list = ['Biomamba','bioinformatics','Biomamba','Biomamba']new_list.count('Biomamba')## 3len(new_list)## 4由于列表的索引结构,我们可以让列表的索引与循环发生一些交互:
while循环:
my_list = ['Biomamba_1','Biomamba_2','Biommaba_3']temp_num =0while temp_num <len(my_list):print(f"这是list中的第{temp_num+1}个元素,它的索引为:{temp_num},它的值为{my_list[temp_num]}") temp_num +=1## 这是list中的第1个元素,它的索引为:0,它的值为Biomamba_1## 这是list中的第2个元素,它的索引为:1,它的值为Biomamba_2## 这是list中的第3个元素,它的索引为:2,它的值为Biommaba_3my_list = ['Biomamba_1','Biomamba_2','Biommaba_3']for temp_ele in my_list:print(f"这是list中的第{my_list.index(temp_ele)+1}个元素,它的索引值为:{my_list.index(temp_ele)+1},它的值为{temp_ele}") temp_num +=1## 这是list中的第1个元素,它的索引值为:1,它的值为Biomamba_1## 这是list中的第2个元素,它的索引值为:2,它的值为Biomamba_2## 这是list中的第3个元素,它的索引值为:3,它的值为Biommaba_3二、元组
元组与列表一样,是可封装多个、不同类型的元素的数据容器。但元组一旦定义,便不可修改、不可修改、不可修改(重说三)。元组的定义方法主要有以下几种方式:
(元素,元素,元素,…,元素,)
('Biomamba',2023,'bioinformatic')## ('Biomamba', 2023, 'bioinformatic')变量名 = (元素,元素,元素,…,元素,)
my_tuple = ('Biomamba',2023,'bioinformatic')print(my_tuple)## ('Biomamba', 2023, 'bioinformatic')变量名称 = ()变量名称 = tuple()
print(tuple())## ()print(type(tuple()))## <class 'tuple'>单元素的元组需要在元素后加上一个”,“,否则默认为字串类型
# 不加逗号print(type(('Biomamba')))# 加上一个逗号## <class 'str'>print(type(('Biomamba',)))## <class 'tuple'>无需过多介绍,与列表的索引使用方法基本一致,甚至各类方法也一致:
my_tuple = ('Biomamba',2023,'Biomamba','bioinformatic')print(my_tuple[0])## Biomambaprint(my_tuple[-1])## bioinformaticprint(my_tuple.index('Biomamba'))## 0print(my_tuple.count('Biomamba'))## 2# 简单元素的元组不可修改my_tuple = ('Biomamba',2023,'Biomamba','bioinformatic')my_tuple[0] ='我是一个修改后的数据'---------------------------------------------------------------------------TypeError Traceback (most recent call last)Cell In[292], line 31# 简单元素的元组不可修改2 my_tuple = ('Biomamba',2023,'Biomamba','bioinformatic')---->3 my_tuple[0] ='我是一个修改后的数据'TypeError:'tuple' object does not support item assignment# 当元组里有列表内容时:my_tuple = ('Biomamba',2023,'Biomamba','bioinformatic',['subBiomamba',2023,'subBiomamba','subbioinformatic'])# 可以进行修改my_tuple[-1][1] ="我是一个修改后的数据"print(my_tuple[-1][1] )三、字符串
字符串格式化的内容我们在5.1.2中已经提前详细介绍过,此处不再重复
9.3.2 字符串索引
注意字符串的索引为对应字节的索引,而非”单词”的索引,例如:
my_chr ='I am Biomamba'print(my_chr[0])## Iprint(my_chr[2])## aprint(my_chr[-1])## aprint(f"注意,空格也占一个字节:这里有一个空格:{my_chr[1]}。")## 注意,空格也占一个字节:这里有一个空格:。# 各类方法也依旧可以使用:print(my_chr.index('a'))# 也支持多个字符的检索## 2print(my_chr.index('Biomamba'))# 返回的索引是多字符的起始索引## 5字符串有一个list与tuple不具备的方法:.replace。顾名思义,这一方法可以做字符串的替换:
my_chr ='I am Biomamba'# 语法为.replace('被替换内容','替换后生成的内容')new_mychr = my_chr.replace('Biomamba','the autuor of this tutorial')print(my_chr)## I am Biomambaprint(new_mychr)# 可以看出,原本的字符串并没有发生改变# 即.replace并不是修改原字符串,而是替换原字符串内容后输出了一个新的字符串## I am the autuor of this tutorial通过.split(分隔符)可以对字符串进行分割,分隔后的数据类型为list
# 例如这里我有三段话,我希望通过句号来分割。my_chr ='I am Biomamba. I am the autuor of this tutorial. Today is Friday'split_result = my_chr.split('.')print(split_result)## ['I am Biomamba', ' I am the autuor of this tutorial', ' Today is Friday']print(type(split_result))# 分割后的结果为返回的list## <class 'list'>用于去除字符串中的一些字符,语法:字符串.strip(字符)
# 不传入任何参数,既是去除字符串首尾空格以及换行符my_chr =' I am Biomamba 'print(my_chr)## I am Biomambaprint(my_chr.strip())# 空格本来就是隐藏的,不太能看出来# 大家可以通过下面的缩进体会:## I am Biomambamy_chr ='I am Biomamba'print(my_chr)## I am Biomambaprint(my_chr.strip("Ia"))# 这里可能和大家预想的不一样,# .strip的逻辑是将输入字符拆分为单个字符,如果字符串的首尾存在,则删除## am Biomambmy_chr ='I am Biomamba'print(my_chr.count('am'))# 这时输入字符作为一个整体用于字数统计## 2len('I am Biomamba')## 13与此前其它数据容器的操作方法类似:
my_chr ='I am Biomamba'for temp_chr in my_chr:print(f"{temp_chr}是字符串的第{my_chr.index(temp_chr)}个字符")## I是字符串的第0个字符## 是字符串的第1个字符## a是字符串的第2个字符## m是字符串的第3个字符## 是字符串的第1个字符## B是字符串的第5个字符## i是字符串的第6个字符## o是字符串的第7个字符## m是字符串的第3个字符## a是字符串的第2个字符## m是字符串的第3个字符## b是字符串的第11个字符## a是字符串的第2个字符四、序列及序列切片
序列为内容连续、有序、可使用下标索引的一类数据容器。我们此前介绍的列表、元组、字符串均属于序列。序列切片:从一个序列中取出一个子序列,序列切片的操作并不会影响序列本身,而是得到一个新的序列。语法为:序列[起始下标:结束下标:步长]
若起始下标留空视为从头开始,若结束下标留空视作截取到结尾,步长为依次取元素的间隔,若步长省略则视为1。注意,取出的内容不包含结束下标本身
my_chr = ['num_1','num_2','num_3','num_4','num_5','num_6','num_7','num_8','num_9']print(my_chr[1:4]) # 省略步长# 这样用起来还是跟R语言非常类似的# 但是不包含索引4本身,即实际取的索引为1、2、3## ['num_2', 'num_3', 'num_4']# 来一个究极省略的,省略起始下标、结束下标、步长:print(my_chr[:])# 这时整个序列会被输出## ['num_1', 'num_2', 'num_3', 'num_4', 'num_5', 'num_6', 'num_7', 'num_8', 'num_9']# 省略起始步长为3切片print(my_chr[::3])## ['num_1', 'num_4', 'num_7']# 在1到6个索引中以步长为2进行切片print(my_chr[0:5:2])## ['num_1', 'num_3', 'num_5']# 反向切片也支持print(my_chr[-1:-6:-2])# 步长也需要为负数# 那么给出的结果顺序为原序列的倒序## ['num_9', 'num_7', 'num_5']五、集合
set)是一个无序的不重复元素。而此前介绍的列表、元组均是有序且可出现重复元素的。由于集合的无序性,自然也就不支持通过下标索引进行访问。但集合支持修改。定义集合字面量{元素,元素,元素,...,元素}定义集合变量变量名称 = {元素,元素,元素,...,元素}定义空集合变量名称 = set()例如:
# 定义集合my_set = {'Biomamba',2023,'Biomamba'}print(my_set)# 可以看到重复的'Biomamba'字样被直接去除## {'Biomamba', 2023}# 添加集合元素my_set = {'Biomamba',2023,'Biomamba'}my_set.add('Study Python') #没有返回值,直接修改原集合print(my_set)# 可以看到Study Python被添加## {'Biomamba', 'Study Python', 2023}# 删除集合元素my_set = {'Biomamba',2023,'Biomamba'}my_set.remove(2023)print(my_set)## {'Biomamba'}由于集合没有下标索引,.pop也就没有任何参数,只能随机取出集合重的一个元素并给出返回值。
# 删除集合元素my_set = {'Biomamba',2023}my_set.pop()## 'Biomamba'print(my_set)## {2023}与各类序列的清空方法类似
my_set = {'Biomamba',2023}my_set.clear()print(my_set)# 清空并不是删除,还会存在一个空集合:## set()# 返回的结果是在my_set1中包含,但在my_set2中不包含的元素my_set1 = {'Biomamba',2023,'Study Python'}my_set2 = {'Biomamba',2023,'Study R'}my_set3 = my_set1.difference(my_set2)print(my_set3)## {'Study Python'}# 但对原集合本身的值无任何影响print(my_set1)## {'Biomamba', 'Study Python', 2023}print(my_set2)## {'Biomamba', 'Study R', 2023}# 在集合1内,删除与集合2相同的元素my_set1 = {'Biomamba',2023,'Study Python'}my_set2 = {'Biomamba',2023,'Study R'}my_set1.difference_update(my_set2)print(my_set1)# 也就是把集合一直接变成上一步的差集,但集合2不会发生变化## {'Study Python'}print(my_set2)## {'Biomamba', 'Study R', 2023}my_set1 = {'Set1','Biomamba',2023,'Study Python'}my_set2 = {'Set2','Biomamba',2023,'Study R'}my_set3 = my_set1.union(my_set2)print(my_set3)## {'Biomamba', 'Set2', 2023, 'Set1', 'Study Python', 'Study R'}len(my_set3)## 6由于集合不存在下标索引,那么while循环的方式无法应用于集合,但for循环依旧可以使用
# 利用for循环遍历打印出集合内的元素my_set = {'Set1','Biomamba',2023,'Study Python'}for temp_set in my_set:print(temp_set)## Set1## Biomamba## Study Python## 2023六、字典
Python中的可变容器模型,且可存储任意类型对象。有些类似于哈希,可以通过特定的键值(key)返回对应的内容(value)字典的key和value可以是任意数据类型,但key不可为字典类型。字典的每个键值对key:value用冒号 : 分割,每个键值对之间用逗号 , 分割,整个字典包括在花括号 {} 中 ,格式如下所示:d = {key1 : value1, key2 : value2 }例如如下的字典:
mydict = {"name":"Biomamba","Date":2023,"major":"Bioinformatics"}print(mydict)## {'name': 'Biomamba', 'Date': 2023, 'major': 'Bioinformatics'}定义空字典:
mydict = {}print(mydict)## {}print(type(mydict))## <class 'dict'>或者用函数定义空字典:
mydict =dict()print(mydict)## {}print(type(mydict))## <class 'dict'>字典会自动去除重复的key所在键值对:
mydict = {"name":"Biomamba","name":"Bioinformatic-base","Date":2023}print(mydict) # 可以看出保留的是最后一个重复的key对应的值## {'name': 'Bioinformatic-base', 'Date': 2023}字典也不支持下标索引,可以通过字典[key]获取对应的值,例如:
mydict = {"name":"Biomamba","Date":2023,"major":"Bioinformatics"}print(mydict["name"])## Biomamba例如value可以是一个子字典:
mydict = {'information':{'language':'python','skill':'scRNA-Seq'},'Date':{'year':2023},'month':5,'Day':4}print(mydict)## {'information': {'language': 'python', 'skill': 'scRNA-Seq'}, 'Date': {'year': 2023}, 'month': 5, 'Day': 4}# 获取嵌套字典的内容,例如查询information里的language对应的值:print(mydict["information"]["language"])## python新增元素
mydict = {"name":"Biomamba"}print(mydict)## {'name': 'Biomamba'}mydict["Date"] =2023print(mydict) # 可以看出无需再赋值给原字典,也可以添加元素## {'name': 'Biomamba', 'Date': 2023}更新元素由于字典的key无法重复,因此对已存在的key执行类似于添加的操作,即可更新value值
mydict = {"name":"Biomamba","Date":2023}print(mydict)## {'name': 'Biomamba', 'Date': 2023}mydict["Date"] =2000print(mydict) # 可以看出无需再赋值给原字典,也可以添加元素## {'name': 'Biomamba', 'Date': 2000}删除同时取出元素
mydict = {"name":"Biomamba","Date":2023}print(mydict)## {'name': 'Biomamba', 'Date': 2023}newdict = mydict.pop('Date')print(mydict)## {'name': 'Biomamba'}print(newdict)## 2023清空字典
mydict = {"name":"Biomamba","Date":2023}print(mydict)## {'name': 'Biomamba', 'Date': 2023}mydict.clear()print(mydict)## {}获取字典中全部的key
mydict = {"name":"Biomamba","Date":2023}mykeys = mydict.keys()print(mykeys)## dict_keys(['name', 'Date'])获取字典的元素数量
mydict = {"name":"Biomamba","Date":2023}len(mydict)## 2通过获得的key遍历字典:
mydict = {"name":"Biomamba","Date":2023,"major":"Bioinformatics"}for mytemp in mydict.keys():print(f"键值{mytemp}对应的value为:{mydict[mytemp]}")## 键值name对应的value为:Biomamba## 键值Date对应的value为:2023## 键值major对应的value为:Bioinformatics直接用for循环遍历字典,获得的临时变量就是key值:
mydict = {"name":"Biomamba","Date":2023,"major":"Bioinformatics"}for mytemp in mydict:print(f"键值{mytemp}对应的value为:{mydict[mytemp]}")## 键值name对应的value为:Biomamba## 键值Date对应的value为:2023## 键值major对应的value为:Bioinformatics因为字典没有下标索引,因此无法直接用于while循环,若通过len来取key的值则有些低效且不优雅:
mydict = {"name":"Biomamba","Date":2023,"major":"Bioinformatics"}mylen =len(mydict)print(mylen)## 3temp_len =0while temp_len < mylen:print(f"键值{list(mydict.keys())[temp_len]}对应的value为:{mydict[list(mydict.keys())[temp_len]]}") temp_len +=1# 多写了很多行## 键值name对应的value为:Biomamba## 键值Date对应的value为:2023## 键值major对应的value为:Bioinformatics七、总结
是否支持下标索引:支持: 列表、元组、字符串 - 序列类型不支持:集合、字典 - 非序列类型
是否支持重复元素:支持:列表、元组、字符串 - 序列类型不支持:集合、字典 - 非序列类型
是否可以修改:支持:列表、集合、字典 - 序列类型不支持:元组、字符串 - 非序列类型
是否支持遍历:for循环:五类数据容器都支持while循环:列表、元组、字符串支持,集合、字典无法直接参与while循环
max():得到最大的元素min():得到最小的元素sorted(容器,[reverse = False]):ASCII码升序排序sorted(容器,[reverse = True]):ASCII码降序排序
list(其它容器)tuple(其它容器)str(其它容器)set(其它容器)
往期回顾

如何联系我们


已有生信基地联系方式的同学无需重复添加

