生活随笔
收集整理的這篇文章主要介紹了
python学习-列表的操作(常用函数均会介绍)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
列表的操作
基本操作
本文中的基本操作有:獲取最大,最小值,獲取某個(gè)元素在列表中出現(xiàn)的次數(shù)。 列表的append,insert,remove,以及下標(biāo)取值,賦值。 列表的擴(kuò)展,以及列表的截取,詳見代碼。 列表的reverse,sort(正序和倒序),sort有個(gè)參數(shù)key,本文沒有介紹。
lst5
= [ 1 , 3 , 5 , 2 , 45 , 0 , 4 , 10 , 2 ]
print ( 'lst5 = ' , lst5
)
print ( 'max(lst5) = ' , max ( lst5
) )
print ( 'min(lst5) = ' , min ( lst5
) )
print ( 'len(lst5) = ' , len ( lst5
) )
print ( '2在lst5中出現(xiàn)了{(lán)cot}次' . format ( cot
= ( lst5
. count
( 2 ) ) ) )
輸出結(jié)果:
lst5
. append
( 2 )
print ( 'lst5 = ' , lst5
)
lst5
. insert
( 1 , 2 )
print ( 'lst5 = ' , lst5
)
lst5
. remove
( 2 )
print ( 'lst5 = ' , lst5
)
lst5
[ 0 ] = 10
print ( 'lst5 = ' , lst5
)
輸出結(jié)果為:
lst5
. reverse
( )
print ( 'lst5 = ' , lst5
)
lst5
. sort
( )
print ( 'lst5 = ' , lst5
)
lst5
. sort
( reverse
= True )
print ( 'lst5 = ' , lst5
)
運(yùn)行結(jié)果:
lst5
. extend
( [ 22 , 13 ] )
print ( 'lst5.extend([22, 13]) = ' , lst5
)
print ( 'lst5[1:]' , lst5
[ 1 : ] )
print ( 'lst5[1:7:2]' , lst5
[ 1 : 7 : 2 ] )
運(yùn)行結(jié)果為:
進(jìn)階
對(duì)于列表有不同的賦值方式,這里做一些介紹。 做一些解釋: range(2, 8)表示的是2,3,4,5,6,7這5個(gè)整數(shù) 使用os.getcwd時(shí),要先引入os,即:import os 列表一些常用功能,這里大概列出來了,大家可以參照代碼仔細(xì)看看。
lst6
= [ i
* i
for i
in range ( 2 , 8 ) ]
print ( 'lst6 = ' , lst6
)
lst7
= [ i
+ j
for i
in 'abc' for j
in '123' ]
print ( 'lst7 = ' , lst7
)
lst8
= [ i
+ j
for j
in 'abc' for i
in '123' ]
print ( 'lst8 = ' , lst8
)
lst9
= [ i
* j
for i
in range ( 2 , 5 ) for j
in range ( 6 , 9 ) ]
print ( 'lst9 = ' , lst9
)
strDir
= os
. getcwd
( )
lst10
= [ i
for i
in os
. listdir
( strDir
) ]
print ( 'lst10 = ' , lst10
)
print ( os
. getcwd
( ) )
print ( os
. path
. abspath
( '.' ) )
print ( os
. path
. abspath
( 'test.txt' ) )
print ( os
. path
. abspath
( '..' ) )
print ( os
. path
. abspath
( os
. curdir
) )
運(yùn)行結(jié)果:
附加內(nèi)容
此章節(jié)引入了函數(shù),定義了一個(gè)函數(shù),關(guān)于函數(shù)的使用,后續(xù)文章會(huì)有介紹。 upper() 把字母改成大寫 lower() 把字母改成小寫 isinstance() 判斷類型,由第二個(gè)參數(shù)決定。不清楚數(shù)據(jù)類型,可以使用print(type(…))來獲取。
def testListGenerate ( ) : lst11
= [ 'Hello' , 'World' , 18 , 'Apple' , None ] lst12
= [ i
. lower
( ) for i
in lst11
if isinstance ( i
, str ) ] lst13
= [ i
. upper
( ) for i
in lst11
if isinstance ( i
, str ) ] print ( 'lst12 = ' , lst12
) print ( 'lst13 = ' , lst13
) testListGenerate
( )
運(yùn)行結(jié)果: 把lst11中的字符串類型數(shù)據(jù)找出,并且改成大寫或者小寫。
總結(jié)
以上是生活随笔 為你收集整理的python学习-列表的操作(常用函数均会介绍) 的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔 網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔 推薦給好友。