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

1.list

聲明一個list很簡單,只需list1=[](儘可能不要將變量名起爲關鍵字list)。
list有以下基本方法:python

(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。app

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則報錯code

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時依據德關鍵字。rem

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

(9)reverse() 反轉數組it

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]
相關文章
相關標籤/搜索