• python27读书笔记0.3


    #-*- coding:utf-8 -*-

    ##D.has_key(k): A predicate that returns True if D has a key k.
    ##D.items(): Returns the contents of dictionary D as a list of two-element tuples(k,v),
    ##D.iteritems():Returns an iterator that generates the values from dictionary D as
    ##a sequence of two-element tuples(k,v).

    ##signals = {0:'red',1:'yellow',2:'green'}
    ##print signals.items()
    ##
    ##for i in signals.items():
    ## print i
    ##
    ##for i,k in signals.items():
    ## print i ,k
    ##
    ##
    ##signalScan = signals.iteritems()
    ##
    ##print signalScan
    ##
    ##for n,name in signalScan:
    ## print "{0:04d}:{1}".format(n,name)
    ## print '--------------------'
    ## print n,name

    ##D.iterkeys():Return an iterator that generates the keys from dictionary D.
    ##D.itervalues():Returns an iterator that generates the values from dictionary D.
    ##D.keys():Returns a list of the key values in dictionary D,in no particular order.
    ##D.popitem():Returns an arbitrary entry from dictionary D as a(key,value) tuple,
    ##and also removes that entry.If D id empty,raises a KeyError exception.
    ##D.setdefault(k,x):If dictionary D has a key equal to k,this method returns the
    ##corresponding value D[k].If D has no key equal to k,the method returns the default
    ##value X.However,unlike the .get() method,it also creates a new key-value pari(k,x) in D.
    ##As with the .get() method,the second argument is optional,and defaults to the value None.
    ##D.values():Returns a list of the values from key-value pairs in dictionary D,in no particular order.
    ##Howerver,if you call both the .items() and .values() methods of a dictionary
    ##without changing that dictionary's contnts between those calls,Python guarantees that
    ##the ordering of the two results will be the same .

    ##signals = {0:'red',1:'yellow',2:'green'}
    ##print signals.values()
    ##print signals.keys()

    ##D.update(D2)
    ##Merge the contents of dictionary D2 into dictionary D.For any key-value pairs that have the
    ##same key in both D and D2,the value for that key in D after this operation will be the
    ##value from D2,not the value form D.

    ##roster={1:'zen',2:'peter',3:'jone',4:'joy'}
    ##newer={3:'bev',5:'GoodN'}
    ##
    ##print '---roster:'
    ##print roster
    ##print '---after update:'
    ##roster.update(newer)
    ##print roster
    ##print '--new:'
    ##print newer

    ##--- Dictionary comprehensions ---
    ##As with list comperhensions,you provide one or more for clauses and an optional if clause.
    ##For all possible combinations of the values in the for clauses that have a true value
    ##for the if clause,two expressions ek and ev are evaluated,and a new dictionary entry is
    ##added with key ek and value ev.

    ## --- Type file:Input and output files ---
    ##To open a file,use this general form:
    ##f = open(name[,mode[,bufsize]]])
    ##name
    ## The path name of the file to be opened,as string.
    ##mode
    ## An optional string specifying what ypu plan to do with the file.
    ##If omitted,you will get read access to the file.In general the value consists of three parts:
    ## General mode,one of :
    ## r:Read access.The file must alread exist.You will not be allowed to write to it.
    ## w:Write access.If there is no file by this name,a new one will be created.
    ## If there is an existing file,it will be deleted!
    ## a:Append access.If there is a file by this name,your initial position will be at the end of
    ## the file,and you will be allowed to write(and read).If there is no file by this name,
    ## a new one will be created .On some systems,all writes to a file with append mode are
    ## added at end of the file,regardless of the current file position.
    ## If you plan to modify the file,append a "+" next.
    ## For example,mode "r+" puts you at the beginning of an existing file and
    ## allows you to write to the file anywhere.
    ## Mode "w+" is the same as "w":it deletes an existing file if there is any,
    ## then creates a new file and givers you write access.
    ## Mode "a+" allows you to write new data at the end of an existing file;if no
    ## file by this name exists,it will crate a new one.
    ## If you handing binary data ,as opposed to lines of text,add "b" at the end of the mod string.
    ## For modes beginning with 'r',you may append a capital 'u' to request universal newline
    ## treatment.This is handy when you are reading files made on a platform with different line
    ## termination conventions.
    ## When reading lines from a file opened in this way,any line terminator(' ',' ',or' ')
    ## will appear in the return value as the standard ' '.Also,files so opened will have an attribute
    ## named .newlines;this attribute will be None initially,but after any line terminators
    ## have been read,it will be a tuple containing all the different line terminator strings seen so far.
    ##
    ##bufsize
    ## Buffer size:this affects when phsical device writes are done,compared to write operations that
    ## your program performs.
    ## In most cases you will probably want to omit this argument.The default is to use
    ## line buffering for terminal-type devices,or some system default for other devices.
    ## Use 0 to force unbuffered operation.This may be inefficient,but any file writes are performed immediately.
    ## Use 1 for line buffering:output lines are written whenever you write a line terminator such as ' '.
    ## Use larger values to specify the actual size of the buffer.
    ## Use a negative value to request the system defaults.
    ##If you are reading text files,and you do not want to worry about the variety of line termination
    ##protocole,you may use a mode value of "U" for "universal line terminator mode."
    ##In this mode,input lines may be terminated with either carriage return(' '),newline(' '),or both,
    ##but the lines you receive will always be terminated with a single newline.
    ##A file is its own iterator.Hence,if you have a file inFile opened for reading,you can use
    ##a for loop that looks like this to iterate over the lines of the file:
    ## for line in inFile:
    ## ....
    ##The variable line will be set to each line of the file in turn.The line terminator character(if any) will be present
    ##in that string .
    ##Other aspects of files:
    ##
    ##Every open file has a current position.Initially ,this will 0L if you opened it for reading or writing,
    ##or the size of the file if you opened it with append access.Each write or read operation
    ##moves this position by the amount read or written.You can also query or set the file position;
    ##Files may use a technique called buffering.Because phusical access to some storage
    ##media(such a disk drivers) takes a relatively long time,Python may employ a storage area called a buffer as a
    ##holding area for data being input or output.
    ##For example,if you are writing data to a disk file,Python may keep the data in the file's buffer area
    ##until the buffer is full and only then actually write it to the physical disk.There are various techniques
    ##for controlling this behavior;

    ##--- Methods on file objects ---
    ##Use these methods on an open file instance F.
    ##F.close()
    ## Close file F. Any unwritten data in the buffer will be flushed. No further operations
    ## will be allowed on thefile unless it is reopened with the open() function.
    ##F.flush()
    ## For buffered files,you can use this method to make sure that all data written to the file has
    ## been physically transmitted to the storage medium.Closing a file will also flush the buffer.
    ## Avoid using this method unless you really need it,as it may make your program less efficient.
    ##F.isatty()
    ## A predicate that tests whether F is a terminal;"tty" is an ancient term that originally meant
    ## "Teletype",but has come to mean any terminal or simulated terminal.
    ##F.read(n)
    ## Read the next n characters from F and return them as a string.
    ## If there are fewer than n characters remaining after your current position,you will get all remaining
    ## characters.If you are at the end of the file,you will get back an empty string ('').
    ## The argument is optional.If omitted,you will get the entire remaining contents of the file as a string.
    ##F.readline(maxlen)
    ## Read the next textline from F and return it as a string,including the line terminator if any.
    ## If you need to limit the maximum size of incoming lines,pass that size limit as the optional maxlen
    ## argument.The default is to return a line of any size (subject to memory limitations).If the line
    ## exceeds maxlen,the file position will be left pointing to the first unread character of that line.
    ##F.readlines()
    ## Read all remaining lines from F and return them as a list of strings,including line terminator characters if any.
    ##F.seek(offset,whence)
    ## Change the file's current position.The value of whence determines how the offset value is used
    ## to change the posititon:
    ## 0:Set the position to offset byetes after the beginning of the file.
    ## 1:Move the current position offset bytes toward the end of the file.
    ## 2:Move the current position offset bytes relative to the end of the file.
    ## For example,for a file f, this operation would set the position to 4 bytes before the end of the file:
    ## f.seek(-4,2)
    ##F.tell()
    ## This method returns the current file position relative to the beginning as a long value.
    ##F.write(s)
    ## Write the contents of string s to file F. This operation will not add terminator characters;
    ## if you want newlines in your file,include them in the string s.
    ##F.writelines(s)
    ## For a sequence s containing strings,write all those strings to F.No line terminators will be add;
    ## you must provide them explicitly if you want them.

    ## --- None:The special placeholder value ---
    ##Python has a unique value called None. This special null value can be used as a placeholder,
    ##or to signify that some value is unknow.
    ##In conversational mode,any expression that evaluates to None is not printed.However,if a value
    ##of None is converted to a string,the result is the string 'None';this may happen ,for example,
    ##in a print statement.
    ##The value None is returned from any function that executes a return statement with no value,or
    ##any function after it exectes its last line if that last line is not a return statement.

    ## --- Operators and expressions ---
    ##Python's operations are shown here from highest precedence to lowest,with a ruled line separation
    ##groups of operators with equal precedence:
    ## (E) Parenhesize expression or tuple.
    ## [E,...] List.
    ## {key:value,...} Dictionary
    ## '...' Convert to string representation
    ## x.attribute Attribute reference.
    ## x[...] Subscript or slice;
    ## f(...) Call function f.
    ## x**y x to the y power.
    ## -x Negation.
    ## ~x Bitwise not(one's complement).
    ## x*y Multiplication
    ## x/y,x//y Division.The"//" form discards the fraction from the result."13.9//5.0"returns the value 2.0
    ## x%y Modulo (remainder of x/y).
    ## x+y Addition,concatenation.
    ## x-y Subtraction.
    ## x<<y x shifted left y bits.
    ## x>>y x shifted right y bits
    ## x&y Bitwise and.
    ## x^y Bitwise exclusive or.
    ## x|y Bitwise or.
    ## x<y,x<=y,x>y,x>=y,x!=y,x==y Comparisons.These operators are all predicates;
    ## x in y,x not in y Test for membership.
    ## x is y,x in not y Test for identity.
    ## not x Boolen "not"
    ## x and y Boolen "and"
    ## x or y Boolen "or"

    ##What is an iterable?
    ##To iterate over a sequence means to visit each element of the sequence,and do some
    ##operation for each element.
    ##In Python,we say that a value is an iterable when your program can iterate over it.
    ##In short,an iterable is a value that represents a sequence of one more values.
    ##All instances of Python's sequence types are iterables.
    ##These types may be referred to as container types: a unicode string is a container for
    ##32-bit characters,and lists and tuples are general-purpose cantainers that can contail
    ##any sequence.

    ## --- Basic functions ---
    ##abs():Absolute value.To find the absolute value of a number x.
    ##all():Are all the elements of an iterable true?
    ##any():Are any of the members of an iterable true?
    ##bin():convert to binary.
    ##This function takes an integer artument and returns a string that represents that
    ##number in binary
    ##bool():Conbert to Boolean
    ##This function tabkes any value x and converts it to a Boolean(True or False) value.
    ##bytearray():Create a byte array
    ##chr():Get the character with a given code
    ##For arguments n in the reage 0 to 255,this function returns a one-character string
    ##containing the character that has code n.
    ##ord():Find the numeric code for a character
    ##cmp():Compare two values
    ##cmp(x,y)
    ##The return value is :
    ## a negative number if x if less than y
    ## Zero if x is equal to y.
    ## A positive number if x is greater than y.
    ##
    ##complex():Convert to complex type
    ##To create a complex number from a real part R and a complex part I:
    ##dict():convert to a dictionary
    ##This function creates a new dictionary from its arguments.
    ##divmod():Quotient and remainder
    ## Examples: divmod(13,5) return (2,3)
    ##enumerate():Step through indices and values of an iterable

    ##L = ['Ministry', 'of', 'Silly', 'Walks']
    ##for where, what in enumerate(L):
    ## print "[{0}] {1}".format(where,what)
    ##
    ##print "---begin with 1 ---"
    ##for where, what in enumerate(L,1):
    ## print "[{0}] {1}".format(where,what)
    ##print "---begin with 3 ---"
    ##for where, what in enumerate(L,3):
    ## print "[{0}] {1}".format(where,what)

    ##filter():Extract qualifying elements from an iterable
    ##This function is useful for removing some of the elements of an iterable.
    ##You must provide a filtering function that takes one arguments and returns
    ##a bool value.

    ##def isOdd(x):
    ## if (x%2) == 1: return True
    ## else: return False
    ##Li=filter(isOdd, [88, 43, 65, -11, 202])
    ##print Li
    ##
    ##def isLetter(c):
    ## return c.isalpha()
    ##print filter(isLetter, "01234abcdeFGHIJ*(&!^")

    ##maybes = [0, 1, (), (2,), 0.0, 0.25]
    ##print filter(None, maybes)
    ##print '---arguments with bool---'
    ##print filter(bool, maybes)

    ##float():Convert to float type
    ##format():Format a value
    ##frozenset():Create a frozen set (an immutable set)
    ##hex():Convert to base 16
    ##Given an integer,this function returns a string display that value in hexadecimal.

    ##print hex(15)
    ##print hex(255)
    ##
    ##int():Convert to int type
    ##input():Read an expression from the user
    ##iter():Produce an iterator over a sequence
    ##len():Number of elements
    ##list():Convert to a list
    ##long():convert to long type
    ##map():Apply a function to each element of an iterable
    ##map(f,s):f is a function that takes one argument and returns a value.
    ## s is any iterable.

    ##def add100(x):
    ## return x+100
    ##Li = map(add100, (44,22,66))
    ##print Li
    ##
    ##def abc(a, b, c):
    ## return a*10000 + b*100 + c
    ##L2 = map(abc, (1,2,3), (4, 5, 6), (7, 8, 9))
    ##print '---- L2 -- '
    ##print L2
    ##
    ##print map(None, range(3), 'abc', [44, 55, 66])

    ##max(): Largest element of an iterable
    ##min(): Smallest element of an iterable
    ##next(): Call an iterator

    ##it = iter(xrange(0,2))
    ##print next(it, 'Done')
    ##print next(it, 'Done')
    ##print next(it, 'Done')
    ##print next(it, 'Done')

    ##oct():Convert to base 8
    ##open():Open a file
    ##ord():Find the numberic code for a character
    ##pow():Exponentiation

    ##print pow(2,4)
    ##print 2**9
    ##print (2**9)%3
    ##print pow(2,9,3)

    ##range():Generate an arithmetic progression as a list
    ##raw_input():Prompt and read a string from the user

    reduce():Sequence reduction
    reversed():Produce a reverse iterator
    round():Round to the nearest integral value
    set():Create an algebraic set
    sorted():Sort a sequence
    str():Convert to str type
    sum():Total the elements of a sequence
    tuple():convert to a tuple.
    type():Return a value's type.
    unichr():Convert a numeric code to a Unicode character.
    unicode():conbert to a Unicode string
    xrange():Arithmetic progression generator
    The xrange() function has exactly the same arguments as the range() function.
    The didfference is that xrange() is a generator,while rang() actually builds a
    list for its result.This means you can use xrange() in situations where you
    want to generate a large series of the values from an arithmetic progression,
    but you do not have engough memory to build that serise as a list.
    zip():Combine multiple sequences
    The purpose of this function is to build a list of tuples from two or more iterables
    of the same length.

  • 相关阅读:
    设置和查看时间
    通过linux ssh远程登录另一台Linux,无需密码,用证书验证
    openssl生成自签名证书
    技术集锦
    centos系统安装中文字体几种方法
    集群中几种session同步解决方案的比较
    leetcode 88. C++ 合并两个有序数组
    CycleGAN --- Unpaired Image-to-Image Translation using Cycle-Consistent Adversarial Networks
    剑指offer---二叉树的深度
    C++基础(2)
  • 原文地址:https://www.cnblogs.com/Alex-Zeng/p/3274348.html
Copyright © 2020-2023  润新知