li = ["one","two"]
print(li.pop) #<built-in method pop of list object at 0x01E8A490>
print(getattr(li,"pop")) #<built-in method pop of list object at 0x01E8A490>
getattr(li,"append")("three")
print(li) #['one', 'two', 'three']
print(type(getattr(TupleTest,"main")) == types.FunctionType) #True
print(getattr(li,"abc","defaultValue")) #defaultValue
(1)li.pop获取列表的pop方法的引用,getattr(li,"pop")也是获取列表pop方法的引用。
(2)getattr(li,"append")("three") 获取列表的append方法的引用,并append一个three到li中。
(3)getattr(li,"abc","defaultValue") 由于列表中没有abc属性,所以会返回默认的defaultValue。 6.过滤列表
过来列表的语法:[mapping-expression for element in source-list if filter-expression]
以if开头的是过滤表达式,过滤表达式返回值为真或假,在过滤表达式返回为真的元素都可以包含在映射中
li = ['a','mpilgrim','foo','b','a','b','d','d']
print([e for e in li if len(e)>1]) #['mpilgrim', 'foo']
print([e for e in li if e!='d']) #['a', 'mpilgrim', 'foo', 'b', 'a', 'b']
print([e for e in li if li.count(e)==1]) #['mpilgrim', 'foo']
(1)筛选出元素长度大于1的。
(2)过滤掉d。
(3)筛选出在列表中出现1次数的元素。 7.and 和 or的特殊性质
在Python中,and和or执行逻辑演算,但它们并不返回布尔值,而是返回它们实际进行比较的值之一
print('a' and 'b') #b
print('' and 'b') #''
print('a' and 'b' and 'c') #c
print('a' or 'b') #a
print('' or 'b') #b
print('' or [] or {}) #{}
(1)使用and时,从左到右运算,0、''、[]、()、{}、None在布尔环境中为假,其他值都为真。
(2)如果布尔环境中摸个值为假,则and返回第一个假值。
(3)如果所有值都为真,and返回最后一个正值。
(4)or同样是从左到右运算,如果有一个值为真,or立即返回该值。
(5)所有值都为假,or返回最后一个假值。