ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

python入门4

2021-11-28 23:32:28  阅读:157  来源: 互联网

标签:入门 python step 列表 lst print hello lst2


1.为什么需要列表

 

 

a=10 #变量存储的是一个对象的引用
lst=['hello','world',98]
print(id(lst))
print(type(lst))
print(lst)

 

 2.列表的创建

 

 

'''创建列表的第一种方式,使用[]'''
lst =['hello','world',98]
print(lst)
'''创建列表的第二种方式,使用内置函数list()'''
lst2=(['hello','world',90])
print(lst2)

 

3.列表的特点

 

 

lst=['hello','world',90,'hello']
print(lst)
print(lst[0],lst[-4])

 

 4.获取指定元素的索引

 

 

lst=['hello','world',98,'hello']
print(lst.index('hello'))

#print(lst.index('pyhton')) ValueError: 'pyhton' is not in list
#print(lst.index('hello',1,3)) ValueError: 'hello' is not in list
print(lst.index('hello',1,4))

 

 

5.获取列表中的多个元素,切片操作

 

 

lst=[10,20,30,40,50,60,70,80]
#start=1,stop=6,step1
print('原列表',id(lst))
lst2=lst[1:6:1]
print('切的片段:',id(lst2))
print(lst[1:6])#默认step=1
#start=1,stop=6,step=2
print(lst[1:6:2])
#stop=6,step=2,start采用默认
print(lst[:6:2])
#start=1,step=2,stop采用默认
print(lst[1::2])
print('-----step步长为负数的情况----------')
print('原列表',lst)
print(lst[::-1])
#start=-7,stop省略,step=1
print(lst[7::-1])
#start=6,stop=0,step=-2
print(lst[7:0:-2])

 

 6.列表元素的判断和遍历

 

 

print('p' in 'python')
print('k' not in 'python')
lst=[10,20,'python','hello']
print(10 not in lst)

 

 7.列表元素的添加操作

 

 

lst=[10,20,30]
print('添加元素之前:',lst,id(lst))
lst.append(100)
print('添加元素之后:',lst,id(lst))
lst2=['hello','world']
#lst.append(lst2) [10, 20, 30, 100, ['hello', 'world']]

lst.extend(lst2)#向列表的末尾一次性添加多个元素
print(lst)

#在任意位置添加一个元素
lst.insert(1,90)
print(lst)

lst3=['True','False','hello']
#在任意位置上添加多个元素
lst[1:]=lst3
print(lst)

 

标签:入门,python,step,列表,lst,print,hello,lst2
来源: https://www.cnblogs.com/liuyi13535496566/p/15617194.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有