1. 程式人生 > >python基礎教程_學習筆記2:序列-2

python基礎教程_學習筆記2:序列-2

序列-2

通用序列操作

序列相加

通過加號對列表進行連線操作;

列表

>>> [1,3,4]+[2,5,8]

[1, 3, 4, 2, 5, 8]

字串

>>> '134'+'258'

'134258'

元組

>>> (1,2,3)+(2,5,8)

(1, 2, 3, 2, 5, 8)

元素資料型別不同的列表

>>> [[1,3],[3,9]]+[[2,2],'abc']

[[1, 3], [3, 9], [2, 2], 'abc']

元素資料型別不同的元組

>>> ('245',1,[5,8])+([3,4],'5',(5,9))

('245', 1, [5, 8], [3, 4], '5', (5, 9))

>>> [2]+[3,5,9]+[10]

[2, 3, 5, 9, 10]

連續相加

>>> [2]+[3,5,9]+[10]

[2, 3, 5, 9, 10]

不同的序列相加

Traceback (most recent call last):

  File "<pyshell#10>", line 1, in <module>

    '123'+[5,8]

TypeError: cannot concatenate 'str' and 'list' objects

>>> [5,8]+(2,5,8)

Traceback (most recent call last):

  File "<pyshell#11>", line 1, in <module>

    [5,8]+(2,5,8)

TypeError: can only concatenate list (not "tuple") to list

>>> '123'+(2,5,8)

Traceback (most recent call last):

  File "<pyshell#12>", line 1, in <module>

    '123'+(2,5,8)

TypeError: cannot concatenate 'str' and 'tuple' objects

可見:

相同型別的序列可以相加,儘管序列中元素的資料型別是不同的;

不同型別的序列不可以相加;

乘法

用數字x乘以一個序列會生成新的序列,在新的序列中,原來的序列被重置x次;

>>> 'string'*5

'stringstringstringstringstring'

>>> ('1','2','3')*5

('1', '2', '3', '1', '2', '3', '1', '2', '3', '1', '2', '3', '1', '2', '3')

>>> [1,'2',3]*5

[1, '2', 3, 1, '2', 3, 1, '2', 3, 1, '2', 3, 1, '2', 3]

序列相乘後生成的新序列,型別不變;

None、空列表和初始化

空列表可以簡單地通過兩個中括號進行表示([])。但如果想一個佔用10個元素空間,卻不包括任何有用內容的列表,需要使用None。它是python內建值,確切含義是“這裡什麼也沒用”。即:

>>> [None]*10

[None, None, None, None, None, None, None, None, None, None]

成員資格

為了檢查一個值是否在序列中,可以使用in運算子。

這個運算子檢查某個條件是否為真,然後返回相應的值,條件真則返回True,假則返回False;這樣的運算子叫做布林運算子,真值叫布林值。

>>> permission='rw'

>>> 'w' in permission

True

>>> 'x' in permission

False

>>> users=['signjing','sj']

>>> raw_input('Enter your name: ') in users

Enter your name: sinjing

False

>>> raw_input('Enter your name: ') in users

Enter your name: sj

True

>>> class1=[

['stud1',18],

['stud2',20],

['stud3',22],

['stud4',17]

]

>>> student1=['stud3',22]

>>> student2=['stud5',28]

>>> student1 in class1

True

>>> student2 in class1

False

長度、最大值、最小值

內建函式lenminmax非常有用;

len函式返回序列中所含元素的數量;

min函式和max函式則返回序列中最小和最大的元素。

>>> class1=[

['stud1',18],

['stud2',20],

['stud3',22],

['stud4',17]

]

>>> min(class1)

['stud1', 18]

>>> max(class1)

['stud4', 17]

>>> len(class1)

4

>>> numbers=[11,33,24]

>>> min(numbers)

11

>>> max(numbers)

33

>>> len(numbers)

3

存在的疑問

學習的過程中難免有疑問,暫且記錄下來。

1序列相乘後得到的序列型別不變,但單元素的元組進行乘法後得到的不是元組;

>>> ('string')*5

'stringstringstringstringstring'

>>> (5)*5

25

對元組進行成員資格檢查,得到的結果與預想不一致;

>>> (2,3,9) in (1,2,3,9,19)

False