python学习记录之1026

来源:互联网 发布:怎样入驻淘宝达人 编辑:程序博客网 时间:2024/06/04 19:23

<span style="font-size:18px;">Last login: Mon Oct 26 12:28:18 on consoleQXdeMacBook-Pro:~ qx$ cd Desktop/workspace/QXdeMacBook-Pro:workspace qx$ lsarrayconvert.cdeduplication.coverflowtestzhishuconvertdeduplicationgreppythontest.txtzhishu.cppQXdeMacBook-Pro:workspace qx$ pythonPython 2.7.6 (default, Sep  9 2014, 15:04:36) [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwinType "help", "copyright", "credits" or "license" for more information.>>> def f(x):...     return x*x... >>> map(f,(1,2,3))[1, 4, 9]>>> map(f,[1,2,3,4])[1, 4, 9, 16]>>> map(str,[1,2,3,5,6,8])['1', '2', '3', '5', '6', '8']>>> def add(x,y):...     return x+y... >>> reduce(add,[1,2,3,4])10>>> def char2num(s):...     return {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}[s]... >>> def str2int(s):...     return reduce(lambda x,y:x*10+y, map(char2num,s))... >>> str2int('1948348')1948348>>> def nameConverse(l):...     return l[0:1].upper()+l[1:].lower()... >>> map(nameConverse,['adam','LISA','barT'])['Adam', 'Lisa', 'Bart']>>> def calc(x,y):...     return x*y... >>> def prod(l):...     return reduce(calc,l)... >>> prod([1,2,3,4])24>>> prod([2,3,4,5])120>>> def is_odd(n):...     return n%2==1... >>> filter(is_odd,[1,2,3,4,5,6,7,8])[1, 3, 5, 7]>>> def not_empty(s):...     return s and s.strip()... >>> filter(not_empty,['a','b','',None,' ',' bn ',])['a', 'b', ' bn ']>>> >>> ''.strip()''>>> 'a'.strip()'a'>>> '   bnhhjh'.strip()'bnhhjh'>>> '   bnhhjh   '.strip()'bnhhjh'>>> 'bn' and '   bn   ''   bn   '>>> 'bd' and ''''>>> 'bd' and 'dhvjh''dhvjh'>>> 'bd' and 'jh''jh'>>> 'ffk  fdhjh    dfhd   fhfhdj'.strip()'ffk  fdhjh    dfhd   fhfhdj'>>> 'abc' and 'bcd''bcd'>>> '' and 'bcd'''>>> 'v' and 'ffdfi''ffdfi'>>> def is_prime(x):...     for n in range(2,x):...             if x%n==0:...                     return False...     return True... >>> filter(is_prime,range(1,101))[1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]>>> def is_prime(x):...     for n in range(2,x):...             if x%n==0:...                     return True...     return False... >>> filter(is_prime,range(1,101))[4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 22, 24, 25, 26, 27, 28, 30, 32, 33, 34, 35, 36, 38, 39, 40, 42, 44, 45, 46, 48, 49, 50, 51, 52, 54, 55, 56, 57, 58, 60, 62, 63, 64, 65, 66, 68, 69, 70, 72, 74, 75, 76, 77, 78, 80, 81, 82, 84, 85, 86, 87, 88, 90, 91, 92, 93, 94, 95, 96, 98, 99, 100]>>> def out_prime(x):...     if x==1:...             return True...     for n in range(2,x):...             if x%n==0:...                     return True...     return False... >>> filter(out_prime,range(1,101))[1, 4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 22, 24, 25, 26, 27, 28, 30, 32, 33, 34, 35, 36, 38, 39, 40, 42, 44, 45, 46, 48, 49, 50, 51, 52, 54, 55, 56, 57, 58, 60, 62, 63, 64, 65, 66, 68, 69, 70, 72, 74, 75, 76, 77, 78, 80, 81, 82, 84, 85, 86, 87, 88, 90, 91, 92, 93, 94, 95, 96, 98, 99, 100]>>> print [x for x in range(1,101) if not [p for p in range(2,x) if x%p==0]][1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]>>> print [x for x in range(1,101) if [p for p in range(2,x) if x%p==0]][4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 22, 24, 25, 26, 27, 28, 30, 32, 33, 34, 35, 36, 38, 39, 40, 42, 44, 45, 46, 48, 49, 50, 51, 52, 54, 55, 56, 57, 58, 60, 62, 63, 64, 65, 66, 68, 69, 70, 72, 74, 75, 76, 77, 78, 80, 81, 82, 84, 85, 86, 87, 88, 90, 91, 92, 93, 94, 95, 96, 98, 99, 100]>>> def out_prime(x):...     if x==1:...             return True...     for n in range(2,x):...             return x%n==0... >>> filter(out_prime,range(1,101))[1, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100]>>> sorted([36,5,21,9])[5, 9, 21, 36]>>> def cmp_ignore_case(s1,s2):...     u1=s1.upper()...     u2=s2.upper()...     if u1<u2:...             return -1...     if u1>u2:...             return 1...     return 0... >>> sorted(['bob','about','Zoo','Credit'],cmp_ignore_case)['about', 'bob', 'Credit', 'Zoo']>>> def calc_sum(*args):...     ax=0...     for n in args:  ...             ax=ax+n...     return ax... >>> calc_sum(1,2,3,4)10>>> l=[1,2,3,4]>>> calc_sum(*l)10>>> def lazy_sum(*args):...     def sum():...             ax=0...             for n in args:...                     ax=ax+n...             return ax...     return sum... >>> lazy_sum(1,2,3,4)<function sum at 0x109275668>>>> f=lazy_sum(1,2,3,4)>>> f<function sum at 0x1092756e0>>>> f()10>>> f<function sum at 0x1092756e0>>>> f1=lazy_sum(1,2,3,4)>>> >>> f1<function sum at 0x10925baa0>>>> f1()10>>> def count():...     fs=[]...     for i in range(1,4):...             def f():...                     return i*i...             fs.append(f)...     return fs... >>> f1=count()>>> f1[<function f at 0x1092757d0>, <function f at 0x109275848>, <function f at 0x1092758c0>]>>> f1()Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: 'list' object is not callable>>> f1,f2,f3=count()>>> f1<function f at 0x10925baa0>>>> f2<function f at 0x109275668>>>> f3<function f at 0x109275938>>>> f1()9>>> f2()9>>> f3()9>>> def count():...     fs=[]...     for i in range(1,4):...             def f(j):...                     def g():...                             return j*j...                     return g...             fs.append(f(i))...     return fs... >>> f1,f2,f3=count()>>> f1()1>>> f2()4>>> f3()9>>> def now():...     print '2015-10-26'... >>> f=now>>> f()2015-10-26>>> now.__name__'now'>>> f.__name__'now'>>> def log(func):...     def wrapper(*args,**kw):...             print 'call %s():' % func.__name__...             return func(*args,**kw)...     return wrapper... >>> @log... def now():...     print '2015-10-26'... >>> now()call now():2015-10-26>>> now=log(now)>>> >>> def log(text):...     def decorator(func):...             def wrapper(*args,**kw):...                     print '%s %s():' % (text, func.__name__)...                     return func(*args,**kw)...             return wrapper...     return decorator... >>> @log('execute')... def now():...     print 'qx'... >>> now()execute now():qx>>> def log(text1,text2):...     def decorator(func):...             def wrapper(*args,**kw):...                     print '%s %s():' % (text1, func.__name__)...                     return func(*args,**kw)...                     print '%s %s():' % (text2, func.__name__)...             return wrapper...     return decorator... >>> @log('begin','end')... def now():...     print 222... >>> now()begin now():222>>> import functools>>> def log(text1,text2):...     def decorator(func):...             @functools.wraps(func)...             def wrapper(*args,**kw):...                     print '%s call' % (text1)...                     return func(*args,**kw)...                     print '%s call' % (text2)...             return wrapper...     return decorator... >>> @log('begin','end')... def test():...     print 'Qx'... >>> test()begin callQx>>> import functools>>> def log(text):...     def decorator(func):...             @functools.wraps(func)...             def wrapper(*args,**kw):...                     return func(*args,**kw)...                     print '%s call' % (text)...             return wrapper...     return decorator... >>> @log('end')... def test():...     print 'Qx'... >>> test()Qx>>> import functools>>> def log(text1,text2):...     def decorator(func):...             @functools.wraps(func)...             def wrapper(*args,**kw):...                     print '%s call:' % text1...                     return func(*args,**kw)...             print '% call:' % text2...             return wrapper...     return decorator... >>> log('begin','end')<function decorator at 0x109275a28>>>> @log('begin','end')... def test():...     print 11... Traceback (most recent call last):  File "<stdin>", line 1, in <module>  File "<stdin>", line 7, in decoratorTypeError: %c requires int or char>>> import functools>>> def log(text1,text2):...     def decorator(func):...             @functools.wraps(func)...             def wrapper(*args,**kw):...                     print '%s call:' % text1...                     return func(*args,**kw)...             print '%s call:' % text2...             return wrapper...     return decorator... >>> @log('begin','end')... def test():...     print 11... end call:>>> test()begin call:11>>> import functools>>> def log(text1,text2):...     def decorator(func):...             @functools.wraps(func)...             def wrapper(*args,**kw):...                     print '%s call:' % text1...                     func(*args,**kw)...                     print '%s call:' % text2...                     return...             return wrapper...     return decorator... >>> @log('begin','end')... def test():...     print 22... >>> test()begin call:22end call:>>> def log(text='execute'):...     def decorator(func):...             def wrapper(*args,**kw):...                     print '%s %s():' % (text,func.__name__)...                     return func(*args,**kw)...             return wrapper...     return decorator... >>> @log... def f():...     pass... >>> f()Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: decorator() takes exactly 1 argument (0 given)>>> @log('execute')... def f():...     pass... >>> f()execute f():>>> def log(text):...     if callable(text)==False:...             def decorator(func):...                     def wrapper(*args,**kw):...                             print '%s %s():' % (text,func.__name__)...                             return func(*args,**kw)...                     return wrapper...             return decorator...     else:...             def wrapper(*args,**kw):...                     print 'call %s():' % func.__name__...                     return wrapper... >>> @log... def f():...     pass... >>> f()Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: 'NoneType' object is not callable>>> def log(text):...     if callable(text)==False:...             def decorator(func):...                     def wrapper(*args,**kw):...                             print '%s %s():' % (text,func.__name__)...                             return func(*args,**kw)...                     return wrapper...             return decorator...     else:...             def wrapper(*args,**kw):...                     print 'call %s():' % func.__name__...                     return func(*args,**kw)...             return wrapper... >>> @log... def f():...     pass... >>> f()Traceback (most recent call last):  File "<stdin>", line 1, in <module>  File "<stdin>", line 11, in wrapperNameError: global name 'func' is not defined>>> def log(text):...     if callable(text)==False:...             def decorator(func):...                     def wrapper(*args,**kw):...                             print '%s %s():' % (text,func.__name__)...                             return func(*args,**kw)...                     return wrapper...             return decorator...     else:...             def wrapper(*args,**kw):...                     print 'call %s():' % func.__name__...                     return text(*args,**kw)...             return wrapper... >>> @log ... def f():...     pass... >>> f()Traceback (most recent call last):  File "<stdin>", line 1, in <module>  File "<stdin>", line 11, in wrapperNameError: global name 'func' is not defined>>> def log(text):...     if callable(text)==False:...             def decorator(func):...                     def wrapper(*args,**kw):...                             print '%s %s():' % (text,func.__name__)...                             return func(*args,**kw)...                     return wrapper...             return decorator...     else:...             def wrapper(*args,**kw):...                     print 'call %s():' % text.__name__...                     return text(*args,**kw)...             return wrapper... >>> @log... def f():...     pass... >>> f()call f():>>> @log('execute')... def f():...     pass... >>> f()execute f():>>> import functools>>> int2=functools.partial(int, base=2)>>> int2('100000')32>>> int2(10000)Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: int() can't convert non-string with explicit base>>> kw={base:2}Traceback (most recent call last):  File "<stdin>", line 1, in <module>NameError: name 'base' is not defined>>> kw={'base':2}>>> int('10010',**kw)18>>> max2=functools.partial(max,10)>>> max2(5,6,7)10>>> args=(10,5,6,7)>>> max(*args)10>>> </span>

>>> class Student(object):...     def __init__(self,name,score):...             self.name=name...             self.score=score...     def print_score(self):...             print '%s: %d' % (self.name,self.score)... >>> bart=Student('Bart Simpson',59)>>> lisa=Student('Lisa Simpson',87)>>> bart.print_score()Bart Simpson: 59>>> lisa.print_score()Lisa Simpson: 87>>> bart<__main__.Student object at 0x103153950>>>> lisa<__main__.Student object at 0x1031539d0>>>> Student<class '__main__.Student'>>>> bart.age=8>>> bart.age8>>> lisa.ageTraceback (most recent call last):  File "<stdin>", line 1, in <module>AttributeError: 'Student' object has no attribute 'age'>>> lisa.age=9>>> lisa.age9>>> lisa<__main__.Student object at 0x1031539d0>>>> bart<__main__.Student object at 0x103153950>>>> bart=Stduent('Bart Simpson',98)Traceback (most recent call last):  File "<stdin>", line 1, in <module>NameError: name 'Stduent' is not defined>>> bart=Student('Bart Simpson',98)>>> bart.score98>>> bart.score=59>>> bart.score59>>> class Student(object):...     def __init__(self, name, score):...             self.__name=name...             self.__score=score...     def print_score(self):...             print '%s: %s' % (self.__name, self.__score)... >>> bart=Student('Bart Simpson',98)>>> bart.nameTraceback (most recent call last):  File "<stdin>", line 1, in <module>AttributeError: 'Student' object has no attribute 'name'>>> bart.__nameTraceback (most recent call last):  File "<stdin>", line 1, in <module>AttributeError: 'Student' object has no attribute '__name'>>> bart._Student__name'Bart Simpson'>>> class Animal(object):...     def run(self):...             print 'Animal is running...'...     >>> class Dog(Animal):...     def run(self):...             print 'Dog is running...'...     def eat(self):...             print 'Eating meat...'... >>> class Cat(Animal):...     def run(self):...             print 'Cat is running...'... >>> dog1=Dog()>>> dog1.run()Dog is running...>>> cat1=Cat()>>> cat1.run()Cat is running...>>> def run_twice(animal):...     animal.run()...     animal.run()... >>> run_twice(Animal())Animal is running...Animal is running...>>> run_twice(Dog())Dog is running...Dog is running...>>> run_twice(Cat())Cat is running...Cat is running...>>> class Tortoise(Animal):...     def run(self):...             print 'Tortoise is running slowly...'... >>> run_twice(Tortoise())Tortoise is running slowly...Tortoise is running slowly...>>> type(123)<type 'int'>>>> type('123')<type 'str'>>>> type(None)<type 'NoneType'>>>> type(8>9)<type 'bool'>>>> type(abs)<type 'builtin_function_or_method'>>>> a=Animal()>>> type(a)<class '__main__.Animal'>>>> import types>>> type('abc')==type.StringTypeTraceback (most recent call last):  File "<stdin>", line 1, in <module>AttributeError: type object 'type' has no attribute 'StringType'>>> type('abc')==types.StringTypeTrue>>> type(u'abc')==types.StringTypeFalse>>> type(u'abc')==types.UnicodeTypeTrue>>> type([])==types.ListTypeTrue>>> type(())==types.TupleTypeTrue>>> type({})==types.DictTypeTrue>>> type(([]))==types.SetTypeTraceback (most recent call last):  File "<stdin>", line 1, in <module>AttributeError: 'module' object has no attribute 'SetType'>>> type(str)==types.TypeTypeTrue>>> isinstance(u'a',basestring)True>>> dir('abc')['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']>>> dir(dog1)['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'eat', 'run']>>> dir(Animal())['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'run']>>> len('abdcfd')6>>> 'adfjd'.__len__()5>>> class MyObject(object):...     def __init__(self):...             self.x=9...     def power(self):...             return self.x*self.x... >>> obj=MyObject()>>> hasattr(obj,'x')True>>> obj.x9>>> getattr(obj,'x')9>>> hasattr(obj,'y')False>>> setattr(obj,'y',19)>>> getattr(obj,'y')19>>> getattr(obj,'z')Traceback (most recent call last):  File "<stdin>", line 1, in <module>AttributeError: 'MyObject' object has no attribute 'z'>>> fn=getattr(obj,'power')>>> fn<bound method MyObject.power of <__main__.MyObject object at 0x10315b150>>>>> fn()81


  



0 0
原创粉丝点击