国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

pythonic code(1)

2019-11-06 06:14:52
字體:
來源:轉載
供稿:網友
dict.setdefault(key,default)“listcomps”: List comPRehensions provide a concise way to create lists.Testing for Ture Values

(http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#id33) 讀完這篇,理解了多一點東西:

知道tuple,comma is the tuple constructor

知道其他編程語言,變量variable是一個box,一個box放一個值,當b=a時,是把a盒子里的值復制給b這個盒子,python中,1是一個integer object,每個object有一個“name”,”tag“,”label“,當a=2,就是把這個”tag“綁到2上,b=a,就是在2再綁一個tag”b”

知道函數默認參數是在函數定義時候執行的,要在runtime執行,需要在內部初始化, 一般用None

def fun(i,a=None): if a is None: a=[] a.append(i) return a知道dict() build-in takes a list of key/value pairs(2-tuple)知道 listcomps, genexps知道 x,y,z=data是 Tuple unpacking

Dictionary Method: dic.setdefault(), dict.get()

case1: Each dictionary value will be initial a value 0

naive way

mdict={}for (key,price) in data: if key not i n mdict: mdict[key]=0 mdict[key]+=price

clever way: mdict.get(key,default)

mdict={}for (key,price) in data: mdict[key]=(mdict.get(key,0)+price)

case2: Each dictionary value will be a list naive way

mdict={}for (key,price) in data: if key in mdict: mdict[key].append(price) else: mdict[key]=[price]

this does the job more efficiently mdict={}

for (key,price) in data: mdict.setdefault(key,[]).append(price)

List Comprehensions

more consice and clear

# a list for squares of odd 0-9a=[n**2 for i in range(10) if n%2]

Enumerate(faster for big data)

for (idx,item) in mylist: print(idx,item)

“,”.join(str_list) (faster for big data)

mdict=dict(zip(a,b)),mdict.keys(),mdict.values()

sorting with keys

想要安裝某一列排序

def my_key(item): return (item[1], item[3])to_sort.sort(key=my_key)

You can make your own key function, or use any existing one-argument function if applicable:

str.lower to sort alphabetically regarless of case. len to sort on the length of the items (strings or containers). int or float to sort numerically, as with numeric strings like “2”, “123”, “35”.


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 根河市| 长岛县| 卫辉市| 镇沅| 荆门市| 吕梁市| 沂南县| 交城县| 南丹县| 汉阴县| 岳西县| 泰安市| 高要市| 通渭县| 鲁甸县| 内丘县| 靖江市| 丰镇市| 泽库县| 双峰县| 东台市| 南京市| 隆子县| 清镇市| 平和县| 临江市| 年辖:市辖区| 郁南县| 花莲县| 白山市| 塔河县| 虞城县| 南溪县| 宾川县| 米林县| 老河口市| 全州县| 依兰县| 遵化市| 垦利县| 同心县|