1. 程式人生 > >python基礎二之列表和元組(序列相加、乘法、成員資格)

python基礎二之列表和元組(序列相加、乘法、成員資格)

這篇文章記載序列相加、乘法、成員資格等內容。

1、序列相加

看下面的例子:

number1=[1,2,3]
number2=[4,5,6]
add=number1+number2;
print("add:{}".format(add))
str1=["hello"]
str2=["world"]
add2=str1+str2;
add3=number2+str2
print(add2)
print(add3)

輸出結果:

add:[1, 2, 3, 4, 5, 6]
['hello', 'world']
[4, 5, 6, 'world']

一般而言,相同型別的序列可以相加,不同的一般不能相加,例如:

str="hello"
number=[1,2,3]
add=str+number
print(add)

來看看輸出結果:

Traceback (most recent call last):
  File "D:/Python_test/project2/sequence.py", line 77, in <module>
    add=str+number
TypeError: must be str, not list

 顯然,不同型別的序列不能相加。

2、乘法:將這個序列和數x相乘,將重複這個序列x次來建立一個新序列。

a1=[1,2,3,4,5]
a2=a1*3;
str=["hello"]
str2=str*3;
print(a2)
print(str2)

輸出結果是:

['hello', 'hello', 'hello']
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5]

3、成員資格:檢索指定的值是否在序列中,可以用關鍵字in,返回值為布林型。

permission="hello,world"
xajh=["東方不敗","風清揚","令狐沖"]
bool1="hello"in permission;
bool2="python" in permission;
bool3="東方不敗" in xajh;
bool4="任我行" in xajh;
print("bool1:{}".format(bool1))
print("bool2:{}".format(bool2))
print("bool3:{}".format(bool3))
print("bool4:{}".format(bool4))

輸出結果為:

bool1:True
bool2:False
bool3:True
bool4:False

4、長度、最值

python的內建函式len,min,max分別使用來序列中包含元素的個數,最小值和最大值的。例項如下:

numbers=[2,10,4,8,200]
mins=min(numbers);
maxs=max(numbers);
lens=len(numbers);
print("mins:{}".format(mins))
print("maxs:{}".format(maxs))
print("lens:{}".format(lens))

輸出結果如下:

mins:2
maxs:200
lens:5