python中的list,tuple,set和dict(參考python文件)

james發表於2019-02-16

1.list

宣告一個list很簡單,只需list1=[](儘量不要將變數名起為關鍵字list)。
list有如下基本方法:

(1)append(x) 在list的末尾新增一個元素x,並且返回None

list1 = [1, 2, 3, 4]
r = list1.append(5)
print(list1, r)
#[1, 2, 3, 4, 5] None

(2)extend(iterable) 將另一個iterable的物件新增到list尾部,返回值為None。

list1 = [1, 2, 3, 4]
r = list1.extend([5, 6, 7, 8])
print(list1, r)
#[1, 2, 3, 4, 5, 6, 7, 8] None

(3)insert(i,x) 將元素x插入到索引i處,返回值為None。

list1 = [1, 2, 3, 4]
r = list1.insert(4, 5)
print(list1, r)
#[1, 2, 3, 4, 5] None

(4)remove(x) 刪除值為x的元素(值而非索引),刪除成功返回None,若沒有x則報錯

list1 = [1, 2, 3, 4]
r = list1.remove(3)
print(list1, r)
#[1, 2, 4] None


list1 = [1, 2, 3, 4]
r = list1.remove(5)
print(list1, r)


Traceback (most recent call last):
  File "E:/Programs/python/data-structure/list-demo.py", line 2, in <module>
    r = list1.remove(5)
ValueError: list.remove(x): x not in list

(5)pop([i]) 如果傳入引數i,刪除索引i處元素。如果不傳參,刪除尾部的元素。返回值為刪掉的元素。

list1 = [1, 2, 3, 4]
r = list1.pop(3)
print(list1,r)

#[1, 2, 3] 4

(6)clear() 清空陣列所有元素,返回None。相當於list1[:]=[]以及del list1[:]

list1 = [1, 2, 3, 4]
r = list1.clear()
print(list1, r)

#[] None

(7)count(x) 返回x在list中出現的次數

list1 = [1, 2, 3, 4, 1, 2, 3, 4, 2, 4]
r = list1.count(4)
print(r)

#3

(8)sort(key=None, reverse=False) 預設從小到大,如果reverse設為True則為從大到小。key為一個lambda表示式,傳入當前元素,返回sort時依據德關鍵字。

list1 = [{`age`: 20}, {`age`: 15}, {`age`: 18}, {`age`: 25}]
list1.sort(key=lambda stu: stu[`age`])
print(list1)

(9)reverse() 反轉陣列

list1 = [1, 2, 3, 4, 5]
list1.reverse()
print(list1)

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

(10)copy() 淺拷貝陣列,相當於list1[:]

list1 = [1, 2, 3, 4, {`name`: `John`}]
list2 = list1.copy()
list2[4][`name`] = `Mike`
print(list1 is list2)
print(list1)
print(list2)

#
False
[1, 2, 3, 4, {`name`: `Mike`}]
[1, 2, 3, 4, {`name`: `Mike`}]

以上為list常用方法。
list可以作為棧使用。

>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]
(官網程式碼)

也可以作為佇列使用,但是需要匯入collections包的deque

>>> from collections import deque
>>> queue = deque(["Eric", "John", "Michael"])
>>> queue.append("Terry")           # Terry arrives
>>> queue.append("Graham")          # Graham arrives
>>> queue.popleft()                 # The first to arrive now leaves
`Eric`
>>> queue.popleft()                 # The second to arrive now leaves
`John`
>>> queue                           # Remaining queue in order of arrival
deque([`Michael`, `Terry`, `Graham`])

初始化list的小竅門:

list1 = [x ** 2 for x in range(10)]
print(list1)
#[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

list1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
list2 = [num for sub in list1 for num in sub]
print(list1)
print(list2)
#[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
[1, 2, 3, 4, 5, 6, 7, 8, 9]

list1 = [(x, y) for x in range(1, 4) for y in range(x, 4)]
print(list1)
#[(1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)]

matrix = [[1, 2, 4, 5], [5, 6, 7, 8], [9, 10, 11, 12]]
r = [[row[i] for row in matrix] for i in range(4)]
print(r)
#[[1, 5, 9], [2, 6, 10], [4, 7, 11], [5, 8, 12]](官網案例)

del語句:del arr[i]刪除索引為i的元素,del arr[:]為清空陣列,del arr[i:j]為清空i到j之前的元素,包括i不包括j。

遍歷方式

list1 = [1, 2, 3, 4, 5, 6, 7, 8]

for i in range(len(list1)):
    print(i, list1[i])

for i, val in enumerate(list1):
    print(i, val)

2.tuple

tuple1 = () 此時tuple1為tuple型別
tuple2 = (1) 此時tuple2非tuple型別,而是int型別
tuple3 = 1, 或者 tuple3 = (1,) 此時tuple3為tuple型別

tuple1 = ()
tuple2 = (1)
tuple3 = 1,
tuple4 = 1, 2, 3, 4
tuple5 = tuple4, 5
print(type(tuple1))
print(type(tuple2))
print(type(tuple3))
print(type(tuple4))
print(tuple5)

#<class `tuple`>
<class `int`>
<class `tuple`>
<class `tuple`>
((1, 2, 3, 4), 5)

tuple可以使用切片,但是tuple不可變,不能給其中元素重新賦值。

tuple1 = 1, 2, 3, 4, 5, 6
tuple1[2] = 5

#Traceback (most recent call last):
  File "E:/Programs/python/data-structure/list-demo.py", line 2, in <module>
    tuple1[2] = 5
TypeError: `tuple` object does not support item assignment

可以通過以下程式碼實現兩個變數值的互換

x = 5
y = 6

x, y = y, x
print(x)
print(y)

#6
5

3.set

執行set1={}這種語句,set1的型別為dict而非set

set1 = {}
print(type(set1))

#<class `dict`>

當用set建構函式建立set時要注意以下的問題:

set1 = set(`abcedfg`)
print(set1)

#{`f`, `c`, `g`, `e`, `b`, `a`, `d`}

set是無序的,並且其中沒有重複元素,因此可以通過set實現去重。

list1 = [1, 1, 2, 3, 4, 4, 5, 6, 6, 7]
print(list(set(list1)))

#[1, 2, 3, 4, 5, 6, 7]

set可以進行求交集,並集,差集,以及找出只存在於其中一個的元素集合

a = set(`abracadabra`)
b = set(`alacazam`)

print(a)
print(b)

print(a & b)
print(a | b)
print(a - b)
print(a ^ b)

#
{`r`, `b`, `a`, `c`, `d`}
{`z`, `a`, `m`, `c`, `l`}
{`c`, `a`}
{`z`, `r`, `b`, `a`, `m`, `c`, `d`, `l`}
{`r`, `b`, `d`}
{`z`, `m`, `r`, `b`, `d`, `l`}

4.dict

初始化dict,需要將key與value都加上引號:

dict1 = {`name`: `Jero`, `age`: 20}

獲取可採用更簡單的方法

dict2 = dict(name=`Jero`, age=20)

遍歷dict時,有如下選擇

dict1 = {`name`: `Jero`, `age`: 20, `gender`: `male`}

for i in dict1:
    print(i, dict1[i])
#name Jero
age 20
gender male


for val in dict1.values():
    print(val)
#Jero
20
male


for key, val in dict1.items():
    print(key, val)

運算:

list1 = [1, 2, 3]
list2 = [4, 5, 6]

print(list1 * 2)

list1 += list2

print(list1)

#[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6]

相關文章