详述python中list(列表)

00 列表的元素

['hello',3.1415,True,None,58]#字符串,浮点型,关键字,整型
Out[25]: ['hello', 3.1415, True, None, 58]

[[23,2.35,'hello',True],['a',2]] #列表中包含列表
Out[26]: [[23, 2.35, 'hello', True], ['a', 2]]

01 列表的索引

s1=['hello',3.1415,True,None,58]
s1[2] #从0开始往后
Out[28]: True

s1=['hello',3.1415,True,None,58]
s1[-3] #从后往前
Out[40]: True

s2=[[23,2.35,'hello',True],['a',2]]
s2[0][2]
Out[29]: 'hello'

02 列表的切片

s1=['hello',3.1415,True,None,58]
s1[1:4]
Out[31]: [3.1415, True, None]

s1=['hello',3.1415,True,None,58]
s1[1:4:2] #间隔为2
Out[32]: [3.1415, None]

s2=[[23,2.35,'hello',True],['a',2]]
s2[0][1:4]
Out[30]: [2.35, 'hello', True]

03 列表的更改,删减,连接,重复,

s1=['hello',3.1415,True,None,58]
s1[-3]=7 #索引更改
s1
Out[42]: ['hello', 3.1415, 7, None, 58]

s2=[[23,2.35,'hello',True],['a',2]]
s2[0]='world' #索引更改
s2
Out[69]: ['world', ['a', 2]]

s2=[[23,2.35,'hello',True],['a',2]]
s2[0][1:4]=1,2,'world' #切片更改
s2
Out[47]: [[23, 1, 2, 'world'], ['a', 2]]

s1=['hello',3.1415,True,None,25,'hello']
del s1[1:3] #删减
s1
Out[68]: ['hello', None, 25, 'hello']

s0=['A','b']
s1=['hello',3.1415,True]
s2=[[23,'hello',True],['a',2]]
s0+s1 #连接
Out[54]: ['A', 'b', 'hello', 3.1415, True]

s1+s2 #连接
Out[55]: ['hello', 3.1415, True, [23, 'hello', True], ['a', 2]]

s1=['hello',3.1415,True]
s1*2 #重复
Out[51]: ['hello', 3.1415, True, 'hello', 3.1415, True]

s2=[[23,'hello',True],['a',2]]
s2*2 #重复
Out[52]: [[23, 'hello', True], ['a', 2], [23, 'hello', True], ['a', 2]]

04 len,index

s1=['hello',3.1415,True,None,58]
len(s1)
Out[48]: 5

s2=[[23,2.35,'hello',True],['a',2]]
len(s2)
Out[49]: 2

s2=[[23,2.35,'hello',True],['a',2]]
len(s2[0])
Out[64]: 4

s1=['hello',3.1415,True,None,25,'hello']
s1.index('hello')
Out[63]: 0

s2=[[23,2.35,'hello',True],['a',2]]
s2.index([23,2.35,'hello',True])
Out[67]: 0

05 append,insert,remove,sort

s2=[[23,2.35,'hello',True],['a',2]]
s2.append('world') #附加
s2
Out[72]: [[23, 2.35, 'hello', True], ['a', 2], 'world']

s2=[[23,2.35,'hello',True],['a',2]]
s2[0].append('world') #附加
s2
Out[73]: [[23, 2.35, 'hello', True, 'world'], ['a', 2]]

s2=[[23,2.35,'hello',True],['a',2]]
s2.insert(1,'world') #插入
s2
Out[75]: [[23, 2.35, 'hello', True], 'world', ['a', 2]]

s2=[[23,2.35,'hello',True],['a',2]]
s2[0].insert(1,'world') #插入
s2
Out[74]: [[23, 'world', 2.35, 'hello', True], ['a', 2]]

s1=['hello',3.1415,True,None,25,'hello']
s1.remove('hello') #移除
s1
Out[77]: [3.1415, True, None, 25, 'hello']

06 in, not in

s1=['a','c','B']
'B' in s1
Out[3]: True

s1=['a','c','B']
'b' not in s1
Out[4]: True

07 列表的复制

import copy
s1=['a','c','B']
copy.copy(s1)
Out[5]: ['a', 'c', 'B']

08 字符串和tuple(元组)

s0='leslie'
s0[1:4]
Out[7]: 'esl'

s0=tuple('leslie')
s0[1:3]
Out[9]: ('e', 's')

09 循环语法

s1='leslie'
for i in s1:
    print('**'+i+'**')
**l**
**e**
**s**
**l**
**i**
**e**

s1=list('leslie')
for i in s1:
    print('**'+i+'**')
**l**
**e**
**s**
**l**
**i**
**e**

详述python中list(列表)的图1

默认 最新
当前暂无评论,小编等你评论哦!
点赞 1 评论 收藏
关注