Coder Social home page Coder Social logo

master's People

Contributors

devinwon avatar

Watchers

 avatar  avatar

master's Issues

filter

  • filter

names = ['Fred', 'Wilma', 'Barney']
def long_name(name): 
      return len(name) > 5

filter_lst=list(filter(long_name,names))
print(filter_lst)

Output:
>>>['Barney']

list(filter(None, [1, 0, 2, [], '', 'a'])) # discards 0, [] and ''
Output:
>>>[1, 2, 'a']

  • filterfalse

from itertools import filterfalse

which works exactly like the generator filter but keeps only the elements that are False:
Usage without function (None):

list(filterfalse(None, [1, 0, 2, [], '', 'a'])) # discards 1, 2, 'a'
Output:
>>> [0, [], '']

Usage with function

names = ['Fred', 'Wilma', 'Barney'] 
def long_name(name): 
     return len(name) > 5

list(filterfalse(long_name, names))
Output:
>>> ['Fred', 'Wilma']

pyperclip.copy paste()

pyperclip模块有copy() paste()函数,向计算机剪贴板发送文本和接受文本
需要安装
import pyperclip
pyperclip.copy("hello")
print(pyperclip.paste())

hello

list

'''
列表的一些方法
'''
list methods

list('hello')
>>>['h', 'e', 'l', 'l', 'o']
tuple('hello')
>>>('h', 'e', 'l', 'l', 'o')

lst=[1,2,3,"male","female"]

index()

'''
index()方法传入一个值,值在列表中就返回它的下标,没有就报ValueError,
重复值,就返回第一次出现的下标
'''

print(lst.index(3))
> 2

append()

'''
append()将元素添加到尾部
'''

lst.append("new")
print(lst)
> [1, 2, 3, 'male', 'female', 'new']

insert()

'''
insert()将元素添加到列表指定位置
'''

lst.insert(1,"new two")
print(lst)
> [1, 'new two', 2, 3, 'male', 'female', 'new']

如果alist.insert(i,item)中i超出了索引范围,就将这个元素插入到最后,不会报错


pop()

'''
pop()默认将末尾元素弹出,带参数的话表示将所索引位置元素弹出,并且返回这个元素,原来的列表发生变化,如果弹出索引越界,就会报错
'''

>>> lst=[1, 2, 3, 13]
>>> lst.pop(6)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
IndexError: pop index out of range
>>> lst.pop(3)
13

remove()

'''
remove()将传入的元素从列表中删除,元素不在列表中报ValueError
'''

lst.remove("new two")
print(lst)
> [1, 2, 3, 'male', 'female', 'new']

del

#知道待删元素下标,del 删除

del lst[0]
print(lst)
> [2, 3, 'male', 'female', 'new']

sort()

'''
sort()对列表排序
注意:
sort()当场对列表排序,无需lst=lst.sort(reverse=False)这样编码
既有数字,又有字符的无法排序
字符是按ascii码排序
如果是字符,按字母顺序排序,可以使用参数lst.sort(key=str.lower)

'''

mylst=["apple","banana","orange","BBB"]
mylst.sort()
print(mylst)
> ['BBB', 'apple', 'banana', 'orange']
mylst=["apple","banana","orange","BBB"]
mylst.sort(key=str.lower)
print(mylst)
> ['apple', 'banana', 'BBB', 'orange']

count()

lst=[1,2,3,4,1,2,]
lst.count(1) #2


Counter()

 >>> from collections import Counter 
 >>> counterA = Counter(['a','b','b','c']) 
 >>> counterA 
 Counter({'b': 2, 'a': 1, 'c': 1})
>>> dict(counterA)
{1: 2, 2: 1, 3: 1, 4: 2, 5: 1}

Counter is a dictionary where where elements are stored as dictionary keys and their counts are stored as
dictionary values. And as all dictionaries, it is an unordered collection.


insort()

向有序列表中插入元素,保持有序

>>> lst=[0, 1, 2]
>>> import bisect
>>> bisect.insort(lst,1)
>>> lst
[0, 1, 1, 2]
>>> bisect.insort(lst,5)
>>> lst
[0, 1, 1, 2, 5]

combinations(lst,cnt)组合

返回iterable(lst)中长度为cnt的元组组合,返回顺序按iterable中元素顺序排列,note:没有重复的元素
还有排列permutations用法类似

from  itertools import combinations
for val in combinations([1,2,3],2):
  print(val)

Out:

(1, 2)
(1, 3)
(2, 3)

val元组类型

permutations(lst,cnt)排列

from  itertools import permutations
for p in permutations([1,2,3,4],2):
	print(p)

Out:

(1, 2)
(1, 3)
(1, 4)
(2, 1)
(2, 3)
(2, 4)
(3, 1)
(3, 2)
(3, 4)
(4, 1)
(4, 2)
(4, 3)

注意:排列是根据元素位置不同来进行排列,而不是值,如果值存在重复的,排列结果”看上去“也会存在重复的,最好是使用集合

dict

dict methods

dict={"add":"SZ","to":"Tom"}

字典是无序的
不能使用切片
键值对形式存在
通过键访问
常用方法:
keys()、values()、items()分别对应表键,值,键值对

keys()

info={"add":"SZ","class":"lvl1"}
for k in info:
	print(k)
> add
> class

相当于for k in info.keys(),即对键的遍历,同样可以对值遍历

values()

for v in info.values()
        print(v)
> SZ
> lvl1

items()

同样可以对键值对遍历

for k,v in info.items():
	print(k,v)
> add SZ
> class lvl1

get()

如果遍历字典中不存在的键会出错,get()方法可以很好的避免报错,有两个参数:访问的键,不存在的话返回的值

info={"add":"SZ","class":"lvl1"}
#使用info["gender"]访问会报错
print(info.get("gender","Male"))
print(info)
> Male
> {'add': 'SZ', 'class': 'lvl1'}

setdefault()

get()方法不会对原字典改变,如果需要改变原字典,即不存在的键将其加入进去,setdefault()方法可以一步完成

print(info.get("gender","Male"))
print(info)
info.setdefault("gender","female")
print(info)
> {'add': 'SZ', 'class': 'lvl1'}
> {'add': 'SZ', 'class': 'lvl1', 'gender': 'female'}

zip() 将两个相关的序列构成一个字典

t1=(1,2,3)
t2=(4,5,6)
d=dict(zip(t1,t2))

bin()、oct()、hex()、 int()进制转换

python拥有内置的进制转换函数,非常方便

十进制向其他进制的转换

十进制-->二进制

bin(3)
'0b11'

十进制-->八进制

oct(10)
'0o12'

十进制-->十六进制

hex(10)
'0xa'

其他进制向十进制转换

都是通过内置函数int实现,int函数中还有个默认参数base,其值默认为10,表示转换的是十进制数,如果为2,则表示转换的是二进制数,不过需要注意的是,如果需要显示指定base参数,那么第一个参数的数据类型必须为字符串

二进制-->十进制

int('0b11',2)
3

八进制-->十进制

int('0o12',8)
10

十六进制-->十进制

int('0xa',16)
10

sorted 字典-列表嵌套

一. 有时需要经常要对字典进行排序,按键或者按值,按键排序比较简单;例如

dic== {'data5':10,'data1':3, 'data2':1, 'data3':2, 'data4':4}
print('按键排序',sorted(dic.items()))

out:
按键进行排序#返回包含元组的列表
[('data1', 3), ('data2', 1), ('data3', 2), ('data4', 4), ('data5', 10)]
print('将键名提取出来排序\n',sorted(dic),sep='')
注意这里sorted(dic)等同于sorted(dic.keys()),前面关于字典的语法有介绍
print('将值提取出来排序\n',sorted(dic.values()),sep='')

out:
将键名提取出来排序
['data1', 'data2', 'data3', 'data4', 'data5']
将值提取出来排序
[1, 2, 3, 4, 10]

二 按值对字典进行排序

1.

print(sorted(dic.items(),key = lambda x:x[1]))

Out:
[('data2', 1), ('data3', 2), ('data1', 3), ('data4', 4), ('data5', 10)]

不难发现:
sorted(dic.items(),key = lambda x:x[0]) 与
sorted(dic.items())
实现同样的结果,key只接受一个参数,应用对象dic.items()是可迭代的

2.

from operator import itemgetter
print(sorted(dic.items(),key = itemgetter(1)))

Out:
[('data2', 1), ('data3', 2), ('data1', 3), ('data4', 4), ('data5', 10)]

3.

print(sorted(zip(dic.values(),dic.keys())))
注意顺序:在前的为依据进行排序
Out:
[(1, 'data2'), (2, 'data3'), (3, 'data1'), (4, 'data4'), (10, 'data5')]

列表嵌套情况排序

列表嵌套 多重字段 排序

lst=[('01',20),('02',100),('08',90),('03',80),('03',93),('05',80)]

"""
第一种情况
列表中嵌套列表或者元组,
对第一个(子)元素进行排序
"""
"""
lst.sort()
print(lst)
或者,
print(sorted(lst))
"""

"""
第二种情况
列表中嵌套列表或者元组,
对非第一个(子)元素进行排序
"""
"""
print(sorted(lst,key=lambda x:(x[1])))

或者,py3.6中 sort()\ sorted()均没有cmp参数,只有key
def mkcmp(x):
return x[1]
print(sorted(lst,key=mkcmp))

或者
from operator import itemgetter
print(sorted(lst,key=itemgetter(1)))

"""

"""
第三种情况
列表中嵌套列表或者元组,
对元素多字段进行排序
实现对多重进行不同的升降排序,1-升,2-降
print(sorted(lst,key=lambda x:(x[1],-int(x[0]))))
"""

"""
from operator import itemgetter
print(sorted(lst,key=itemgetter(0,1)))
print(sorted(lst,key=itemgetter(1,0)))
"""

"""
第四种情况
列表中字典,
按指定键排序
"""
"""
"""
lst=[{"name":"Joe","age":23,"grade":90},
{"name":"Devin","age":20,"grade":80},
{"name":"Kevin","age":19,"grade":93},
{"name":"Robot","age":18,"grade":80},
{"name":"Amy","age":24,"grade":70},
{"name":"Ham","age":22,"grade":88},
{"name":"Bob","age":23,"grade":82},
{"name":"Aob","age":25,"grade":82}
]

"""
"""
relsort=sorted(lst,key=lambda x :(-(x["grade"]),x['name']))
for v in relsort:
print("{:8}".format(v["name"]),v["grade"])

"""
lst=[(1,2,3),(3,4),(0)]
print(sorted(lst,key=lambda x :len(str(x))))
"""

python+tuling robot weixin autoreply

  • python环境
  • pip install requests
  • pip install itchat
import requests
import itchat
import random

KEY = 'd6a29b9bd7bd40bcaedbf26b5010a050'

def get_response(msg):
    apiUrl = 'http://www.tuling123.com/openapi/api'
    data = {
        'key'    : KEY,
        'info'   : msg,
        'userid' : 'Devin',
        # 'userid' : 'wechat-robot',
    }
    try:
        r = requests.post(apiUrl, data=data).json()
        return r.get('text')
    except:
        return

@itchat.msg_register(itchat.content.TEXT)
def tuling_reply(msg):
    defaultReply = 'I received: ' + msg['Text']
    # robots=['小智','大山','无用']
    # reply = get_response(msg['Text'])+random.choice(robots)
    reply = get_response(msg['Text'])
    return reply or defaultReply

# itchat.auto_login(enableCmdQR=True)
itchat.auto_login(hotReload=True)
itchat.run()

tuling123.com 注册
KEY替换
运行登录微信即可实现自动回复

set

NOTE: {1} creates a set of one element, but {} creates an empty dict. The correct way to create an empty set is set().

Note that the set is not in the same order as the original list; that is because sets are unordered, just like dicts.

| Union

{1, 2, 3, 4, 5} | {3, 4, 5, 6} # {1, 2, 3, 4, 5, 6}
{1, 2, 3, 4, 5}.union({3, 4, 5, 6}) # {1, 2, 3, 4, 5, 6}

& Intersection

{1, 2, 3, 4, 5} & {3, 4, 5, 6} # {3, 4, 5}
{1, 2, 3, 4, 5}.intersection({3, 4, 5, 6}) # {3, 4, 5}

- Difference

{1, 2, 3, 4} - {2, 3, 5} # {1, 4}
{1, 2, 3, 4}.difference({2, 3, 5}) # {1, 4}

^ Symmetric difference with

{1, 2, 3, 4} ^ {2, 3, 5} # {1, 4, 5}
{1, 2, 3, 4}.symmetric_difference({2, 3, 5}) # {1, 4, 5}
equal to (a|b)-(a&b)

>= Superset check

{1, 2} >= {1, 2, 3} # False
{1, 2}.issuperset({1, 2, 3}) # False

<= Subset check

{1, 2} <= {1, 2, 3} # True
{1, 2}.issubset({1, 2, 3}) # True

Disjoint check

{1, 2}.isdisjoint({3, 4}) # True
{1, 2}.isdisjoint({1, 4}) # False

in Existence check

2 in {1,2,3} # True
4 in {1,2,3} # False
4 not in {1,2,3} # True

add ,discard and remove

s = {1,2,3}
s.add(4) # s == {1,2,3,4}

s.discard(3) # s == {1,2,4}
s.discard(5) # s == {1,2,4}

s.remove(2) # s == {1,4}
s.remove(2) # KeyError!

map、reduce

map()是 Python 内置的高阶函数,它接收一个函数 f 和一个 可迭代对象(如list),并通过把函数 f 依次作用在 list 的每个元素上,得到一个新的 list 并返回。

示例用法——分隔的元素列表中元素都转为Int型:
int1,int2=map(int,input().split())

>>> a,b =map(int,input().split())
12 23
>>> a,b
(12, 23)
>>> type(a)
<class 'int'>

这样的话就非常方便

另一个高阶函数reduce(),用法同map()类似,reduce()传入的函数 f 必须接收两个参数,reduce()对list的每个元素反复调用函数f,并返回最终结果值。

from functools import reduce
def func(v1,v2):
     return v1+v1
lst=[1,2,3]
reduce(func,lst)  //6
reduce(func,lst,10)//16

reduce函数将做如下计算:
先计算头两个元素:f(1, 2),结果为3;
再把结果和第3个元素计算:f(3, 3),结果为6;
由于没有更多的元素了,计算结束,返回结果6。

reduce()还可以接收第3个可选参数,作为计算的初始值。如果把初始值设为10,
第一轮计算结果就为11=func(10,1).

可变(mutable)/不可变(immutable)

python的数据基本类型可以分为可变(mutable)、不可变(immutable)
可 变:列表、
不 可 变:整型、字符、元组

可变,就是在内存中的那块内容(value)是否可以被改变。如果是可变的,对对象操作的时候,不需要再在其他地方申请内存,只需要在此对象后面连续申请(+/-)即可,也就是它的address会保持不变,但区域会变长或者变短。

不可变的,在对对象本身操作的时候,必须在内存的另外地方再申请一块区域(因为老区域#不可变#),老的区域就丢弃了(如果还有其他ref,则ref数字减1,类似unix下的hard-link)。

可变

>>> a=[]
>>> b=a
>>> a is b
True
>>> a.append(1)
‘’‘ a的值改变了,同时b的值也改变了,但是内存地址没变’‘’
>>> b
[1]
>>> a is b
True

不可变

>>> c=12
>>> d=c
>>> c is d
True
>>> c+=1
‘’‘由于c,d整型数据不可变,对c+1后,申请另外一块区域,id(c)变了,id(d)不变,对此区域ref数字-1 ’‘’
>>> c
13
>>> d
12
>>> c is d
False       

lamda

lambda表达式是一行函数。
它们在其他语言中也被称为匿名函数。如果你不想在程序中对一个函数使用两次,你也许会想用lambda表达式,它们和普通的函数完全一样。

原型
lambda 参数:返回结果
示例:

    add = lambda x, y: x + y

    print(add(3, 5))
    # Output: 8

一些lambda表达式的应用案例,可以在一些特殊情况下使用:
列表排序

    a = [(1, 2), (4, 1), (9, 10), (13, -3)]
    a.sort(key=lambda x: x[1])

    print(a)
    # Output: [(13, -3), (4, 1), (1, 2), (9, 10)]

列表并行排序
data = zip(list1, list2)
data = sorted(data)
list1, list2 = map(lambda t: list(t), zip(*data))

is ==

is 比较内存中的地址

== 比较的是地址里的值

Talk is cheap,show me the code

>>> a="hello"
>>> b=“hello”
>>> a is b
True
>>> a==b
True

a,b 都指向同一个内存地址

>>> id(a)
23525280
>>> id(b)
23525280
>>> a=[1,2,3]
>>> b=[1,2,3]
>>> a is b
False
>>> a==b
True

a,b 都指向不同的内存地址

>>> id(a)
30703568
>>> id(b)
30703328

如果 c is d 为True
则 c==d 一定为True

我们再看python 的一个细节示例:

>>> a=257
>>> b=257
>>> a is b
False
>>> a==b
True
>>> id(a)
23323344
>>> id(b)
23324304
>>> a=10
>>> b=10
>>> a is b
True
>>> a==b
True
>>> id(a)
1785452480
>>> id(b)
1785452480

小整数池的范围是[-5,257),小整数在python启动时自动建立缓冲,并且不会被清除,就是小整数是全局解释器范围内被重复使用的,大整数在使用完成后会清除来节省内存空间。

认真思考的你可能还会有疑问:关于字符(不可变),与列表(可变)赋值的差别?

str

str methods

center(width)方法,

以width宽度居中显示

>>> s="hello"
>>> s.center(10)
'  hello   '
>>> s.center(3)
'hello'

find()

返回从左至右找到首次满足条件元素的索引,没有找到返回-1

>>> s.find('hello')
0
>>> s.find('h')
0
>>> s.find('l')
2
>>> s.find('w')
-1

没有找到则返回:-1

split(sep)

以sep为分隔符对字符串进行分割,返回分隔后的列表,原字符串不发生变化

>>> s
'hello'
>>> s.split('e')
['h', 'llo']
>>> s
'hello'
>>> s.split('l')
['he', '', 'o']
>>> s
'hello'
>>> s.split('el')
['h', 'lo']
>>> s.split('hello')
['', '']

upper(),lower()方法

返回一个新的字符串,并没有改变原字符串本身

s="hello"
print(s.upper())
print(s)
> HELLO
> hello

如果需要改变原来的,需要重新赋值

isupper(),islower()方法

返回布尔值

print(s.isupper())
> False

isalpha()

只包含字母且非空,返回True

print(“Hello”.isalpha())
> True

isdecimal()

只包含数字且非空,返回True

print(“Hello123”.isdecimal())
print(“123”.isdecimal())
> False
> True

isalnum()

只包含字母数字且非空,返回True

print('123'.isalnum())
print('hello'.isalnum())
print('hello123'.isalnum())
print('hello123$'.isalnum())
> True
> True
> True
> False

isspace()

只包含空格、制表符、换行且非空,返回True

print('   '.isspace())
print('\t'.isspace())
> True
> True

istitle()

只包含大写字母开头,后面都是小写字母的单词,返回True

print('Hello'.istitle())
print('HELLO'.istitle())
print('hello'.istitle())
> True
> False
> False

startswith() 、endswith()

如果调用的字符串以该方法传入的参数字符串开始或者结束,返回True

print(("Hello world").startswith("hello"))
print(("Hello world").endswith("rld"))
> False
> True

join()

join()方法在字符串上调用,参数是字符串列表,返回一个字符串。
返回的字符串是由调用的字符串将列表元素顺序连接起来

print("-".join(['a','b','c']))
> a-b-c

注意,列表元素类型需要是字符型

split()

split()与join()恰好相反,用于分隔字符串,可以安装传入的分隔符进行分割
默认为空格
结果返回一个分隔后各元素组成的列表

print("My name is Devin".split())
print("My_name_is_Devin".split('_'))
> ['My', 'name', 'is', 'Devin']
> ['My', 'name', 'is', 'Devin']

rjust()、ljust()、center()

分别是右对齐,左对齐,居中,默认插入空格对齐文本
第一个参数为整数,表示占据长度,
第二个参数为字符,便是填充字符

print("Hello".rjust(8))
print("Hello".ljust(8))
print("Hello".center(8))
print("Hello".ljust(8,'#'))
>    Hello
> Hello   
>  Hello  
> Hello###

strip()、rstrip()、lstrip()

分别为删除两端,右端,左端空白字符

print("  hello world  ".strip(),'###',sep='')
print("  hello world  ".lstrip(),'###',sep='')
print("  hello world  ".rstrip(),'###',sep='')
>hello world###
>hello world  ###
>  hello world###

format

name="Devin"
age=12
print("{0} is {1} years old".format(name,age))

> Devin is 12 years old
#这里需要注意顺序
print("{name} is my {relationship}".format(relationship="friend",name="Lily"))

> Lily is my friend
#这里与顺序无关
#使用列表
lst=["Math",98]
lst2=["lvl1","lvl2"]
print("my {0[0]} is {0[1]}:{1[1]}".format(lst,lst2))

> my Math is 98:lvl2
'''
填充与对齐
填充常跟对齐一起使用
^、<、>分别是居中、左对齐、右对齐,后面带宽度
:号后面带填充的字符,只能是一个字符,不指定的话默认是用空格填充
'''
print("1234567890")
#默认空格填充,居中对齐
print("{:^10}".format("Hello"))

#指定#填充
print("{:#^10}".format("Hello"))

#右对齐
print("{:<10}".format("Hello"))

#左对齐
print("{:>10}".format("Hello"))

> 1234567890
>   Hello   
> ##Hello###
> Hello     
>      Hello
#精度控制
print("{:.4f}".format(1234.567))

> 1234.5670
#进制转换
#b、d、o、x分别是二进制、十进制、八进制、十六进制
print("{:b}".format(10))
print("{:d}".format(10))
print("{:o}".format(10))
print("{:x}".format(10))

> 1010
> 10
> 12
> a
#千位分隔符
print("{:,}".format(123456))
> 123,456

reference 、copy、deepcopy

example:

oddlst=[1,3,5]
#oddlst2 引用oddlst
oddlst2=oddlst
# 二者结果一样,指向了同一内容
print(oddlst)
print(oddlst2)
> [1, 3, 5]
> [1, 3, 5]
#只对oddlst元素改变
oddlst[0]=7

print(oddlst)
print(oddlst2)
> [7, 3, 5]
> [7, 3, 5]
#oddlst2元素也受到了影响,更加说明指向同一内容

要想各自拥有自己一份独立的内容,避免干扰,对于列表list,元组tuple(二者支持切片)可以这样

>>>oddlst2=oddlst[:]
>>>oddlst is oddlst2
>>>False

由于字典不支持切片,如果需要拷贝,需要copy

import copy
d={"add":"cn","cd":"10000","to":{"name":"Tom"}}
d2=copy.copy(d)
print(d)
print(d2)
> {'add': 'cn', 'cd': '10000', 'to': {'name': 'Tom'}}
> {'add': 'cn', 'cd': '10000', 'to': {'name': 'Tom'}}
d["add"]="usa"
print(d)
print(d2)
> {'add': 'usa', 'cd': '10000', 'to': {'name': 'Tom'}}
> {'add': 'cn', 'cd': '10000', 'to': {'name': 'Tom'}}

列表list,元组tuple使用[:]复制时,相当于copy(),只会复制外层数据,内层的数据仍是引用,如果有嵌套的数据结构,例如列表中的元素仍然是列表的话,内部的表复制的话需要deepcopy()

l=[1,2,[1,2]]
#外层复制
l2=l[:]
print(l)
print(l2)
> [1, 2, [1, 2]]
> [1, 2, [1, 2]]

#对l中内层元素改变

l[2][0]=1000
print(l)
print(l2)
> [1, 2, [1000, 2]]
> [1, 2, [1000, 2]]

#可见l2中内层数据也发生了改变,如果内层数据也需要独立,则使用deepcopy()

*args and **kwargs

并不是必须写成*args**kwargs。 只有变量前面的 *(星号)才是必须的. 你也可以写成*var**vars. 而写成*args **kwargs只是一个通俗的命名约定。

*args

*args **kwargs主要用于函数定义。 你可以将不定数量的参数传递给一个函数。
这里的不定的意思是:预先并不知道, 函数使用者会传递多少个参数给你, 所以在这个场景下使用这两个关键字。 *args 是用来发送一个非键值对的可变数量的参数列表给一个函数.一个例子如下:

def test_var_args(f_arg, *argv):
    print("first normal arg:", f_arg)
    for arg in argv:
        print("another arg through *argv:", arg)

test_var_args('yasoob', 'python', 'eggs', 'test')

Output:

first normal arg: yasoob
another arg through *argv: python
another arg through *argv: eggs
another arg through *argv: test

另一示例

def getsum(*var):
	if var is None:
		return 0
	else:
		s=0
		for v in var:
			s+=v
		return s

print(getsum(1,2,3))
print(getsum())

output:
6
0

**kwargs

**kwargs 允许你将不定长度的键值对, 作为参数传递给一个函数。 如果你想要在一个函数里处理带名字的参数, 你应该使用**kwargs。一个示例如下:

def greet_me(**kwargs):
    for key, value in kwargs.items():
        print("{0} == {1}".format(key, value))


>>> greet_me(name="yasoob")
name == yasoob

现在你可以看出我们怎样在一个函数里, 处理了一个键值对参数了。

使用*args **kwargs 来调用函数

def test_args_kwargs(arg1, arg2, arg3):
    print("arg1:", arg1)
    print("arg2:", arg2)
    print("arg3:", arg3)

使用*args**kwargs来给这个小函数传递参数。

# 首先使用 *args
>>> args = ("two", 3, 5)
>>> test_args_kwargs(*args)
arg1: two
arg2: 3
arg3: 5

# 现在使用 **kwargs:
>>> kwargs = {"arg3": 3, "arg2": "two", "arg1": 5}
>>> test_args_kwargs(**kwargs)
arg1: 5
arg2: two
arg3: 3

heapq,min,max

  • nlargest

import heapq 
numbers=[1, 4, 2, 100, 20, 50, 32, 200, 150, 8] 
print(heapq.nlargest(4, numbers))

Output:
[200, 150, 100, 50]

  • nsmallest

print(heapq.nsmallest(4, numbers))
Output:
[1, 2, 4, 8]

Both nlargest and nsmallest functions take an optional argument (key parameter) for complicated data
structures. The following example shows the use of age property to retrieve the oldest and the youngest people
from people dictionary:

people = [ 
      {'firstname': 'John', 'lastname': 'Doe', 'age': 30}, 
      {'firstname': 'Jane', 'lastname': 'Doe', 'age': 25}, 
      {'firstname': 'Janie', 'lastname': 'Doe', 'age': 10}, 
      {'firstname': 'Jane', 'lastname': 'Roe', 'age': 22}, 
      {'firstname': 'Johnny', 'lastname': 'Doe', 'age': 12}, 
      {'firstname': 'John', 'lastname': 'Roe', 'age': 45} 
 ] 
oldest = heapq.nlargest(2, people, key=lambda s: s['age']) 
print(oldest) 

Output:

 [{'firstname': 'John', 'age': 45, 'lastname': 'Roe'}, {'firstname': 'John', 'age': 30, 
 'lastname': 'Doe'}] 
 youngest = heapq.nsmallest(2, people, key=lambda s: s['age']) 
 print(youngest) 

Output:

 [{'firstname': 'Janie', 'age': 10, 'lastname': 'Doe'}, {'firstname': 'Johnny', 'age': 12, 
 'lastname': 'Doe'}]

堆数据结构最重要的特征是 heap[0] 永远是最小的元素,要查找的元素个数相对比较小的时候,函数 nlargest() 和 nsmallest() 是很合适的。如果你仅仅想查找唯一的最小或最大 (N=1) 的元素的话,那么使用 min() 和max() 函数会更快些。类似的,如果 N 的大小和集合大小接近的时候,通常先排序这个集合然后再使用切片操作会更快点 ( sorted(items)[:N] 或者是 sorted(items)[-N:] )。需要在正确场合使用函nlargest() 和 nsmallest() 才能发挥它们的优势 (如果N 快接近集合大小了,那么使用排序操作会更好些。

return返回多个结果

def profile():
    name = "Danny"
    age = 30
    return name, age

print(type(profile()))
print(profile())
print(profile()[0])
print(profile()[1])
Output:
<class 'tuple'>
('Danny', 30)
Danny
30

装饰器——从函数中返回函数

有时并不需要在一个函数里去执行另一个函数,可以将其作为输出返回出来,示例如下:

def nameEdit(name="张三"):
    def ori():
        return "默认名为张三"

    def after():
        return "你修改了默认名"

    if name == "张三":
        return ori
    else:
        return after

nm = nameEdit()
print(nm)
print(nm())

output:

<function nameEdit.<locals>.ori at 0x0065EB28>
默认名为张三

# 改变参数指向不同的函数

nm = nameEdit(name="Jame")
print(nm)
print(nm())

Output

<function nameEdit.<locals>.after at 0x0066EA08>
你修改了默认名

再次看看这个代码。在if/else语句中我们返回ori和after,而不是ori()和after()。为什么那样?这是因为当你把一对小括号放在后面,这个函数就会执行;然而如果你不放括号在它后面,那它可以被到处传递,并且可以赋值给别的变量而不去执行它。

yield

def fib(n):
	a,b=0,1
	while a<n:
		yield a
		a,b=b,a+b

for v in fib(3):
	print(v)

Out:

0
1
1
2

简单地讲,yield 的作用就是把一个函数变成一个 generator,带有 yield 的函数不再是一个普通函数,Python 解释器会将其视为一个 generator,调用 fab(3) 不会执行 fab 函数,而是返回一个 iterable 对象!在 for 循环执行时,每次循环都会执行 fab 函数内部的代码,执行到 yield b 时,fab 函数就返回一个迭代值,下次迭代时,代码从 yield b 的下一条语句继续执行,而函数的本地变量看起来和上次中断执行前是完全一样的,于是函数继续执行,直到再次遇到 yield。

可以手动调用 fab(3) 的 __next__() 方法(因为 fab(3) 是一个 generator 对象,该对象具有__next__()方法,python2为next()方法),这样我们就可以更清楚地看到 fab 的执行流程:

g=fib(4)
print(g.__next__())
print(g.__next__())
print(g.__next__())
print(g.__next__())
print(g.__next__())

Out:

0
1
1
2
3

一个带有 yield 的函数就是一个 generator,它和普通函数不同,生成一个 generator 看起来像函数调用,但不会执行任何函数代码,直到对其调用__next__()(在 for 循环中会自动调用 __next__())才开始执行。虽然执行流程仍按函数的流程执行,但每执行到一个 yield 语句就会中断,并返回一个迭代值,下次执行时从 yield 的下一个语句继续执行。看起来就好像一个函数在正常执行的过程中被 yield 中断了数次,每次中断都会通过 yield 返回当前的迭代值。

yield 的好处是显而易见的,把一个函数改写为一个 generator 就获得了迭代能力,比起用类的实例保存状态来计算下一个 __next__() 的值,不仅代码简洁,而且执行流程异常清晰。

def yield_test(n):  
    for i in range(n):  
        yield call(i)  
#生成函数

def call(i):  
    return i*2  

#使用for循环  
#注意yield_test(5)的写法
for i in yield_test(5):  
    print(i)

Output:

0
2
4
6
8

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.