Beginning Python From Novice To Professional读书笔记

  1. The last character in a raw string can’t be a backslash, If the last character(before the final quote) is a backslash, Python won’t know whether to end the string or not.raw字符串最后一个字符不能是\
  2. 如果确实需要最后一个字符是\,需要将\放到另外一个字符串里

>>> print r"c:\Prpgram Files\foo\bar" "\\"

c:\Prpgram Files\foo\bar\

  1. Modules are extensions that can be Imported into Python to extend its capabilities.
  2. You can change a list, but you can’t change a tuple. Tuple can be used as dictionary keys, but lists can’t. Because you aren’t allowed to modify keys.
  3. A string is just a sequence of characters. The index 0 refers to the first element.
  4. Slicing: the first index is the number of the first element you want to include, however, the last index is the number of the first element after you slice. In short, the first is inclusive, and the second is exclusive.
  5. if the slice continues to the end of sequence, you may simply leave out the last index. Numbers[-3:], if you want to copy the entire sequence, you may leave out both indices. Numbers[:]
  6. The step length is one – the slice ‘moves’ from one element to the next, returning all the elements between the start and end
  7. The step size can be negative, which means extracting the elements from right to left: when using a negative step size, you have to have a first limit(start index) that is higher than the second one.
  8. Lists are mutable—that is, you can change their contents.
  9. list works with all kinds of sequence, not just string:list(‘hello’), if you want to convert a list of characters back to string, use ‘’.join(somelist)
  10. the pop method removes an element(by default the last one) from the list and returns it
  11. If you want to iterate over a sequence in reverse, you can use the reversed function. This function doesn’t return a list. Though, it returns an iterator.
  12. The sort method is used to sort lists in place. Sorting “in place” means changing the original so its elements are in sorted order, rather than simply returning a sorted copy of the list. Notes that sort modifies list but return nothing!
  13. sorted function can be used on any sequence, but will always return a list
  14. Tuple can’t be changed!
  15. Strings are immutable, so all kinds of item or slice assignments are illegal
  16. if no separator is supplied, the default is to split on all runs of consecutive whitespace characters(spaces, tabs, newlines, and so on)
  17. Keys are unique within a dictionary (and any other kind of mapping), while values may not be.
  18. You can assign a value to a key even if that key isn’t in the dictionary to begin with. A new item will be created.
  19. when you replace a value in the copy, the original is unaffected. However, if you modify a value (in place, without replacing it), the original is changed as well because the same value is stored there.
  20. When you use get to access a nonexistent key, there is no exception. Instead, you get the value None. If the key is there, get works like ordinary dictionary lookup.
  21. Popitem pops off a random item because dictionaries don’t have a “last element” or any other whatsoever.
  22. Setdefault sets the value corresponding to the given key If it is not already in the dictionary. When the key is missing, setdefault returns the default and updates the dictionary accordingly. If the key is present, its value is returned and the dictionary is left unchanged. The default is optional, as with get; if it is left out, None is used.
  23. The update method updates one dictionary with the items of another: The items in the supplied dictionary are added to the old one, overwriting any items there with the same keys.
  24. In general, you should not use += with strings, especially if you are building a large string piece by piece in a loop. Each addition and assignment needs to create a new string, and that takes time, making your program slower. A much better approach is to append the small strings to a list, and use the string method join to create the big string when your list is finished.
  25. The standard values False and None, numeric zero of all types (including float, long, and so on), empty sequences (such as empty strings, tuples, and lists), and empty dictionaries are all false. Everything else is interrupted as true, including the special value True.
  26. Is tests for identity, rather than equality. X=y=[1, 2, 3], z = [1, 2, 3], x==z(True), x ix z (False). The variables x and y have been bound to the same list, while z is simply bound to another list that happens to contain the same values in the same order. They may be equal, but they aren’t the same object.
  27. Use == to see if two objects are equal, and use is to see if they are identical (the same object). Caution: Avoid the use of is with basic, immutable values such as numbers and strings. The result is unpredictable because of the way Python handles these objects internally.
  28. Short-Circuit logic: the Boolean operators are often called logic operator, the second value is sometimes “short-circuited”
  29. A string with one space is not empty, and therefore not false.
  30. Zips parallel iterate together the sequences, returning a list of tuples. The zip function works with as many as you want, it stops when the shortest sequence is “used up”
  31. Enumerate iterate over index-value pairs, where the indices are supplied automatically
  32. Reverse a string: ‘’.join(reversed(‘someStr’))
  33. >>> girls = ['alice', 'bernice', 'clarice']

>>> boys = ['chris', 'arnold', 'bob']

>>> [b '+' g for b in boys for g in girls if b[0] == g[0] ]

 

>>> letterGirls ={}

>>> for girl in girls:

      letterGirls.setdefault(girl[0], []).append(girl)           

>>> print [b + '+' + g for b in boys for g in letterGirls[b[0]]]

  1. Del just delete the name, not the list itself.
  2. page = download_page() freqs = compute_frequencies(page) for word, freq in freqs: print word, freq
  3. >>> def fibs(num):

            result = [0, 1]

            for i in range(num-2):

                        result.append(result[-2] + result[-1])

  1. return result
  2. The variables you write after your function name in def statements are often called formal parameters of the function, while the values you supply when you call the function are called the actual parameters or arguments.
  3. Assigning a new value to a parameter inside a function won’t change the outside world at all.
  4. Strings (and numbers and tuples) are immutable. You can’t modify them
  5. When two variables refer to the same list, they refer to the same list, if you want to avoid this, you have to make a copy of the list. When you do slicing on a sequence, the returned slice is always a copy. If you make a slice of the entire list you get a copy.
  6. Names that are local to a function, including parameters, do not clash with names outside of the function (that is, global ones)
  7. if you really want to modify your parameter, you can wrap your value in a list.
  8. Each time a function is called, a new namespace is created for that specific call
  9. the map function maps one sequence into another (of the same length) by applying a function to each of the elements.
  10. Object means a collection of data (attributes) with a set of methods for accessing and manipulating those data.
  11. self refers to the object itself
  12. Methods have their first parameter bound to the instance they belong to: you don’t have supply it.
  13. If a method is implemented differently by two or more of the superclasses, you must be careful about the order of these superclasses (in the class statement): The methods in the earlier classes override the methods in the latter ones.
  14. If an exception is raised inside a function, and isn’t handled there, it propagates to the place where the function was called, If it isn’t handled there either, it continues to propagating until it reaches the main program (the global scope), and if there is no exception handler there, the program halts with an error message and some information about what went wrong (a stack trace).
  15. Static methods and class methods are created by wrapping methods in objects of the staticmethod and classmethod types, respectively. Static methods are defined without self arguments, and can be called directly on the class itself. Class methods are defined with a self-like parameter normally called cls/ You an call class methods directly on the class object too, but the cls parameter then automatically is bound to the class.
  16. Any function that contains a yield statement is called a generator. Each time a value is yielded (with yield), the function freezes: That is, it stops its execution at exactly that point and waits to be reawakened. When it is, it resumes its execution at the point where it stopped.
  17. A generator is a function that contains the keyword yield. When it is called, the code in the function body is not executed. Instead, an iterator is returned. Each time a value is requested, the code in the generator is executed until a yield or a return is encountered.
  18. To find out what a module contains, you can use dir function, which lists all the attributes of an object.
  19. When you look up an element in a shelf object, the object is reconstructed from its stored version; and when you assign an element to a key, it is stored.
  20. The match function will report a match if the pattern matches the beginning of a string; the pattern is not required to match the entire string.
  21. When you use binary mode, Python gives you exactly the contents found in the file.
  22. Xreadlines works almost like readlines except that it doesn’t read all the lines into a list.
  23. The syntax print >> file, text prints the text to the given file object
  24. You can create a connection directly to a database file – which will be created if it doesn’t exist—by supplying a file name.
  25. A socket is basically an “information channel” with a program on both ends
  26. A server socket uses its bind method followed by a call to listen to given address. A client socket can then connect to the server by using its connect method with the same address as used in bind.
  27. Urlretrieve returns a tuple(filename, headers), where filename is the name of the local file(this name is created automatically by urllib), and headers contains some information about the remote file.
  28. Screen scraping is a process whereby your program downloads Web pages and extracts information from them. Conceptually, the technique is very simple. You download the data and analyze it, you could, simply use urllib, get the Web page’s HTML source, and then use regular expressions or some such to extract the information.
  29. if you define methods called startup and teardown, they will be executed before and after each of the test methods, so you can use them to provide common initialization and cleanup code.
  30. The call to renderPDF.drawToFile saves your PDf file in the current directory
  31. A SAX parser reads through the XML file and telss you what it sees(text, tags, attributes), storing only small parts of the document at a time; this makes SAX simple, fast, and memory-efficient; DOM constructs a data structure (the document tree), which represents the entire document. This is slower and requires more memory, but can be useful if you want to manipulate the structure of your document
  32. The set_teminator method is used to set the line terminator to “\r\n”, which is the commonly used line terminator in network protocols
  33. SimpleXMLRPCSever instantiated with a tuple of the form (servername, port). The server name is the name of the machine on which the server will run (you can use an empty string here to indicate localhost), the port number can be any port you have access to.
  34. List.append(object) equivalent to list[len(list):len(list)] = [object]
  35. List.extend(sequence) equivalent to list[len(list):len(list)] = sequence
  36. Dict.fromkeys(seq[, val]) returns a dictionary with keys from seq and values set to val (default None)
  37. Dict.setdefault(key[, default]) rerurns dict[key] if it exists; otherwise it returns the given default value (default None) and binds dict[key] to it.
  38. The return statement halts the execution of a function and returns a value. If no value is supplied, None is returned.
  39. The yield statement temporarily halts the execution of a generator and yields a value. A generator is a form of iterator and can be used in for loops
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值