Python複習筆記跳躍版

1.列表和字符串,以及字典的使用方法和區別
Python字符串html

>>> s = 'abcdef'
>>> s[1:5]
'bcde'

**str = 'Hello World!'**
 
print str           # 輸出完整字符串
print str[0]        # 輸出字符串中的第一個字符
print str[2:5]      # 輸出字符串中第三個至第五個之間的字符串
print str[2:]       # 輸出從第三個字符開始的字符串
print str * 2       # 輸出字符串兩次
print str + "TEST"  # 輸出鏈接的字符串

以上實例輸出結果:python

Hello World!
H
Hello World!TEST

Python列表
List(列表) 是 Python 中使用最頻繁的數據類型。
列表能夠完成大多數集合類的數據結構實現。它支持字符,數字,字符串甚至能夠包含列表(即嵌套)。
列表用 [ ] 標識,是 python 最通用的複合數據類型。數據結構

**list = [ 'runoob', 786 , 2.23, 'john', 70.2 ]**
tinylist = [123, 'john']
 
print list               # 輸出完整列表
print list[0]            # 輸出列表的第一個元素
print list[1:3]          # 輸出第二個至第三個元素 
print list[2:]           # 輸出從第三個開始至列表末尾的全部元素
print tinylist * 2       # 輸出列表兩次
print list + tinylist    # 打印組合的列表

以上實例輸出結果:函數

['runoob', 786, 2.23, 'john', 70.2]

Python 字典
字典(dictionary)是除列表之外python之中最靈活的內置數據結構類型。列表是有序的對象集合,字典是無序的對象集合。
二者之間的區別在於:字典當中的元素是經過鍵來存取的,而不是經過偏移存取。
字典用"{ }"標識。字典由索引(key)和它對應的值value組成。測試

dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"

tinydict = {'name':'john','code':6743,'dept':'sales'}

print (dict['one'])          # 輸出鍵爲'one' 的值
print (dict[2])              # 輸出鍵爲 2 的值
print (tinydict)             # 輸出完整的字典
print (tinydict.keys())      # 輸出全部鍵
print (tinydict.values())    # 輸出全部值

輸出結果爲:google

This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']

2. Python的內置函數code

2.1內置函數set( )
set() 函數建立一個無序不重複元素集,可進行關係測試,刪除重複數據,還能夠計算交集、差集、並集等。
set 語法:htm

class set([iterable])

參數說明:
iterable -- 可迭代對象對象;
返回值
返回新的集合對象。對象

>>>x = set('runoob')
>>> y = set('google')
>>> x, y
(set(['b', 'r', 'u', 'o', 'n']), set(['e', 'o', 'g', 'l']))   # 重複的被刪除
>>> x & y         # 交集
set(['o'])
>>> x | y         # 並集
set(['b', 'e', 'g', 'l', 'o', 'n', 'r', 'u'])
>>> x - y         # 差集
set(['r', 'b', 'u', 'n'])

2.1內置函數sorted( )
sorted() 函數對全部可迭代的對象進行排序操做
sort 與 sorted 區別:
sort 是應用在 list 上的方法,sorted 能夠對全部可迭代的對象進行排序操做。
list 的 sort 方法返回的是對已經存在的列表進行操做,而內建函數 sorted 方法返回的是一個新的 list,而不是在原來的基礎上進行的操做。
sorted 語法排序

sorted(iterable[, cmp[, key[, reverse]]])

參數說明:
iterable -- 可迭代對象。
cmp -- 比較的函數,這個具備兩個參數,參數的值都是從可迭代對象中取出,此函數必須遵照的規則爲,大於則返回1,小於則返回-1,等於則返回0。
key -- 主要是用來進行比較的元素,只有一個參數,具體的函數的參數就是取自於可迭代對象中,指定可迭代對象中的一個元素來進行排序。
reverse -- 排序規則,reverse = True 降序 , reverse = False 升序(默認)。
返回值
返回從新排序的列表。

>>>a = [5,7,6,3,4,1,2]
>>> b = sorted(a)       # 保留原列表
>>> a 
[5, 7, 6, 3, 4, 1, 2]
>>> b
[1, 2, 3, 4, 5, 6, 7]

難點:https://www.runoob.com/python...

>>> L=[('b',2),('a',1),('c',3),('d',4)]
>>> sorted(L, cmp=lambda x,y:cmp(x[1],y[1]))   # 利用cmp函數
[('a', 1), ('b', 2), ('c', 3), ('d', 4)]
>>> sorted(L, key=lambda x:x[1])               # 利用key
[('a', 1), ('b', 2), ('c', 3), ('d', 4)]

例二:

students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
print(sorted(students, key=lambda s: s[2]))
print(type(students))
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
<class 'list'>
相關文章
相關標籤/搜索