python ==》列表
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python ==》列表相关的知识,希望对你有一定的参考价值。
#定义列表
l=[1,‘a‘,[3,4]] #l=list([1,‘a‘,[3,4]])
#取值:通过列表的索引取值。
print (l[0])
print (l[1])
print(l[2][0])
循环 while
l=[1,2,3,[4,5]]
count = 0
while count < len(l):
print(l[count])
count+=1
循环 for
l=[1,2,3,[4,5]]
for count in range (len(l)):
print (l[count])
把列表的里元素分别打印出来。方法一:
l=[1,2,3,[4,5]]
for count in range (len(l)):
if type (l[count])is list:
for i in range(len(l[count])):
print (l[count][i])
else:
print(l[count])
‘ok‘
方法二
l=[1,2,3,[4,5]]
l_size = len(l) #把列表的长度定义为一个变量
for index in range (l_size):
value=l[index]
if type (value)is list:
for i in range(len(value)):
print (value[i])
else:
print(value)
ok
切片 读操作
l= [‘ab‘,1,2,‘hello‘]
print(l[1:3])#顾头不顾尾
print (l)
追加
l= [‘ab‘,1,2,‘hello‘]
l.append(‘world‘)
print(l)
列表
l = [1,2,3] # l =list([1,2,3])
print (type(l))
print (l)
优先掌握:
索引取值
l = [1,2,3,4,5]
print (l[0])
切片
l = [1,2,3,4,5]
print (l[1:4])
print (l)
print (l[1:4:2]) #指定步长
print(l[-2:])
print (l[-3:-1])
追加
hobbies = [‘paly‘,‘eat‘,‘sleep‘,‘study‘]
hobbies.append(‘girls‘)
print (hobbies)
删除
hobbies = [‘play‘,‘eat‘,‘sleep‘,‘study‘]
del hobbies[1] #利用索引 也是单纯的删除。
hobbies.remove(‘sleep‘) #单纯的删除,指定元素来删除。
x=hobbies.pop() #不是单纯的删除,是删除之后有个返回值,我们可以用一个变量来接收返回值。
print (x)
print (hobbies)
队列:先进先出
x = []
x.append(‘first‘)
x.append(‘second‘)
x.append(‘third‘)
print (x)
print(x.pop(0))
print(x.pop(0))
print(x.pop(0))
堆栈
x = []
x.append(‘first‘)
x.append(‘second‘)
x.append(‘third‘)
print (x)
print(x.pop())
print(x.pop())
print(x.pop())
长度
hobbies = [‘eat‘,‘sleep‘,‘plal‘]
print (len(hobbies))
包含
hobbies = [‘play‘,‘eat‘,‘sleep‘]
print (‘study‘ in hobbies)
掌握
hobbies = [‘play‘,‘eat‘,‘sleep‘,‘eat‘]
insert:插入
hobbies.insert(1,‘walk‘)
hobbies.insert(0,[‘walk1‘,‘walk2‘])
print(hobbies)
计数
print(hobbies.count(‘eat‘,))
扩展
hobbies.extend([‘walk‘,‘walk‘,‘walk‘])
print (hobbies)
寻找索引
print (hobbies.index(‘eat‘))
了解
clear 清空
hobbies.clear()
print (hobbies)
copy 复制
hobbies.copy()
reverse 翻转
hobbies.reverse()
sort 排序
hobbies.sort()
以上是关于python ==》列表的主要内容,如果未能解决你的问题,请参考以下文章