列表的定义
定义空列表:
方式1(常用): 列表名 = []
方式2: 列表名 = list()
定义非空列表:
方式1(常用): 列表名 = [元素1 , 元素2 , 元素3 , ...]
方式2: 列表名 = [ [元素1,元素2] , [元素1,元素2] , ...]
列表的操作
添加元素
添加一个元素到列表末尾: 列表名.append(元素)
添加多个元素多列表末尾: 列表名.extend(容器)
在指定位置插入指定元素: 列表名.insert(索引位置,元素)
删除元素
根据索引删除对应位置上的元素: 列表名.pop(索引) 或者 del 列表名[索引]
直接删除指定元素: 列表名.remove(元素)
清空列表所有元素: 列表名.clear()
修改元素
根据索引修改指定位置上的元素: 列表名[索引] = 新值
查询元素
根据索引查询指定位置上的元素: 列表名[索引]
查询列表中元素的总个数: length = len(列表名)
查询指定元素出现的次数: count = 列表名.count(元素) 注意: 查找的元素如果不存在就返回0
查询指定元素的索引位置: index = 列表名.index(元素) 注意: 如果查找的元素不存在就报错: ValueError: 60 is not in list
元组的定义
定义空元组:
方式1(常用): 元组名 = ()
方式2: 元组名 = tuple()
定义非空元组:
方式1(常用): 元组名 = (元素1 , 元素2 , 元素3 , ...)
方式2: 元组名 = ( (元素1,元素2) , (元素1,元素2) , ...)
注意:如果元组中只有一个元素需要加逗号
定义1个元素的元组: 元组名 = (元素 ,)
练习题
下列一段话里"t"开头的单词有多少?
part = """Is there in the whole world a being who would have the
right to forgive and could forgive? I don’t want harmony. From love for
humanity I don’t want it. I would rather be left with the unavenged
suffering. I would rather remain with my unavenged suffering and
unsatisfied indignation, _even if I were wrong_. Besides, too high a
price is asked for harmony; it’s beyond our means to pay so much to
enter on it. And so I hasten to give back my entrance ticket, and if I
am an honest man I am bound to give it back as soon as possible. And
that I am doing. It’s not God that I don’t accept, Alyosha, only I most
respectfully return Him the ticket.”
"""
word = part.split(' ')
count = 0
for a in word:
if a[0] =='t' or a[0]=='T':
count+=1
print(f'"t"开头的单词有{count}个')