Python interview - Any, All, Cmp, Dict, Enumerate

Python built-in function, 之前介绍了比如reduce, map, zip, filter。这里总结下any,all,顺带记录下cmp,dict,enumerate,isinstance。


*** iterable:tuple,list,string字符串,等等

*** 0, '', False 都是非真


Python Doc:

any(iterable)
Return True if any element of the iterable is true. If the iterable is empty, return False. Equivalent to:

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False

文档中描述,Any方法可以对iterable的对象进行操作。如果有一个值是true,那么返回True,否则返回False。如果是空,返回False。


print any([0, 0, 0]) # False 都是0,0不是true

b = ['1', {'a': '3'}, 'abc']
print any(type(i) is dict for i in b) # True, 有一个dic字典
b = ['1', 'abc']
print any(type(i) is dict for i in b) # False,没有字典
print any((0, '', False)) # False, 0,'',False,都是非true




Python Doc:

all(iterable)
Return True if all elements of the iterable are true (or if the iterable is empty). Equivalent to:

def all(iterable):
    for element in iterable:
        if not element:
            return False
    return True

文档中描述,All方法可以对iterable的对象进行操作。如果所有的值是true,那么返回True,否则返回False。如果是空,也返回True。


print all([1, 2, 3, 4, -1]) # 都是真
print all([1, 2, 0, 4, -1]) # 有0
print all(['a', 'b', '', 'd']) # 有''
print all((0, 1, 2, 3)) # 有0
print all([]) # empty返回True




Python Doc:

cmp(x, y)
Compare the two objects x and y and return an integer according to the outcome. The return value is negative if x < y, zero if x == y and strictly positive if x > y.


文档中描述,cmp方法比较两个对象x和y。x<y的时候,返回负数;x==y的时候,返回0;x>y的时候,返回正数。


print cmp(1, 2) # -1
print cmp(1, 1) # 0
print cmp(5, 2) # 1
print cmp('abcd','a') # 1
print cmp('bcd','a') # 1
print cmp('a', 'a') # 0
print cmp('aaaa', 'a') # 1
print cmp('a', 'aaa') # -1
print cmp('aaabc', 'b') # -1
print 'aaabc' > 'a' # True
print 'aaabc' > 'b' # False



Python Doc:

enumerate(sequence[, start=0])
Return an enumerate object. sequence must be a sequence, an iterator, or some other object which supports iteration. The next() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the corresponding value obtained from iterating over iterable. enumerate() is useful for obtaining an indexed series: (0, seq[0]), (1, seq[1]), (2, seq[2])


enumerate方法,在遍历的同时,给出index和value值。
def enumerate(collection): 
    'Generates an indexed series:  (0,coll[0]), (1,coll[1]) ...'      
     i = 0 
     it = iter(collection) 
     while 1: 
     yield (i, it.next()) 
     i += 1


如下的例子,enumerate方法更加整洁,易懂。得到的结果是一样的
list = ['A', 'B', 'C']

for i in range (0,len(list)):
    print i ,list[i]


for key, value in enumerate(list):
    print key, value

特殊情况,其实返回的是一个tuple,只是是一个index,value的对,然后赋值。

for something in enumerate(list):
    print something

(0, 'A')
(1, 'B')
(2, 'C')




Python Doc:

isinstance(object, classinfo)
Return true if the object argument is an instance of the classinfo argument, or of a (direct or indirect) subclass thereof. Also return true if classinfo is a type object (new-style class) and object is an object of that type or of a (direct or indirect) subclass thereof. If object is not a class instance or an object of the given type, the function always returns false. If classinfo is neither a class object nor a type object, it may be a tuple of class or type objects, or may recursively contain other such tuples (other sequence types are not accepted). If classinfo is not a class, type, or tuple of classes, types, and such tuples, a TypeError exception is raised.

如果object参数是classinfo参数的一个实例或者子类(直接或者间接)的,返回True。
当然,想检验一个对象的类型的时候,还是可以使用type()函数

if type(obj) == type(dict):
    # do stuff
elif type(obj) == type(list):
    # do other stuff

用instance()的话
if isinstance(obj, dict):
    # do stuff
elif isinstance(obj, list):
    # do other stuff

字符串,str,unicode都继承basestring
print isinstance(u'3.0', unicode) # True
print isinstance('3.0', str) # True
print isinstance(u'3.0', str) # False
print isinstance(u'3.0', str) # False
print isinstance(u'3.0', basestring) # True
print isinstance('3.0', basestring) # True

数字,int,float。 用(int,float)的tuple来判断是否是int或者float。
print isinstance('3', (int, float)) # False
print isinstance(3.0, (int, float)) # True
print isinstance(3, (int, float)) # True
print isinstance(3.0, float) # True
print isinstance(3.0, int) # False
print isinstance(3, float) # False
print isinstance(3, int) # True




Python Doc:

class dict([arg])
Return a new dictionary initialized from an optional positional argument or from a set of keyword arguments. If no arguments are given, return a new empty dictionary. If the positional argument arg is a mapping object, return a dictionary mapping the same keys to the same values as does the mapping object. Otherwise the positional argument must be a sequence, a container that supports iteration, or an iterator object. The elements of the argument must each also be of one of those kinds, and each must in turn contain exactly two objects. The first is used as a key in the new dictionary, and the second as the key’s value. If a given key is seen more than once, the last value associated with it is retained in the new dictionary.

If keyword arguments are given, the keywords themselves with their associated values are added as items to the dictionary. If a key is specified both in the positional argument and as a keyword argument, the value associated with the keyword is retained in the dictionary. For example, these all return a dictionary equal to {"one": 1, "two": 2}:


dict方法直接生成字典。

print dict(one=1, two=2) # {'two': 2, 'one': 1} # only works for keys that are valid Python identifiers

print dict({'one': 1, 'two': 2}) # {'two': 2, 'one': 1}
print dict(zip(('one', 'two'), (1, 2))) # {'two': 2, 'one': 1}
print dict([['two', 2], ['one', 1]]) # {'two': 2, 'one': 1}

temp = dict([['two', 2], ['one', 1]])
print temp['one'] # 1
temp['one'] = 10
print temp # {'two': 2, 'one': 10}
temp['three'] = 3
print len(temp) # 3
del temp['two']
print temp # {'three': 3, 'one': 10}
print temp.keys() # ['three', 'one']
print temp.values() # [3, 10]
print temp.items() # [('three', 3), ('one', 10)]# 直接返回列表对象
print temp.iteritems() # <dictionary-itemiterator object at 0x10a8606d8> # 返回迭代器对象,占用空间少
print temp.iterkeys() # <dictionary-keyiterator object at 0x10a8606d8> # 同理
print temp.itervalues() # <dictionary-valueiterator object at 0x10a8606d8> # 同理

for key, value in temp.items():
    print key, value

for key, value in temp.iteritems():
    print key, value
 Copy 和 Update 

dict1 = {"b" : "blue", "c" : "color", "g" : "gray", "r" : "red"}
dict2 = {"g" : "green", "o" : "orange"}
dict3 = dict1.copy()     #copy() 就是复制
del dict1["b"]
print dict3 # {'c': 'color', 'b': 'blue', 'r': 'red', 'g': 'gray'}
print dict1 # {'c': 'color', 'r': 'red', 'g': 'gray'}
dict1.update(dict2)     #update() 根据dict2的key/value来重写已有的数据
print dict1 # {'c': 'color', 'b': 'blue', 'g': 'green', 'r': 'red', 'o': 'orange'}

 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值