pythonic code(1)

  • 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-9
a=[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”.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值