Are you using Python like this?

Source: Internet
Author: User

Learning Python 1.1...

Statement:
Part of the content in this article is listed below the blog of copy arrogant OX:

3 4 5 6 7 8 9 10 ==> http://harmony.relax.blogbus.com/logs/12303417.html

12 ====> http://my.chinaunix.net/space.php? Uid = 1721137 & Do = Blog & id = 274710

Http://linuxtoy.org/archives/python-collection-tips.html

Thanks to the authors.

More tips, http://www.siafoo.net/article/52

1. Select and or as the condition

I think all those who have used C are right (A> 1 )? Is a special liking for this expression. What should I do in Python?

In [15]: True and 1 or 2Out[15]: 1In [16]: False  and 1 or 2Out[16]: 2

Another case is that you often need to write such code: if (a) C = A else c = B;

How to express it in Python: c = A or B

In [10]: a = 0In [11]: b = 1In [12]: c = a or bIn [13]: cOut[13]: 1

What about and?

In [1]: a= 1 and 2In [2]: aOut[2]: 2In [3]: a = 1 or 2In [4]: aOut[4]: 1In [5]: a = 1 and 0In [6]: aOut[6]: 0

2. Zip + dict

In [17]: a = "ABCD"In [18]: b = "abcd"In [19]: zip(a,b)Out[19]: [('A', 'a'), ('B', 'b'), ('C', 'c'), ('D', 'd')]In [20]: dict(zip(a,b))Out[20]: {'A': 'a', 'B': 'b', 'C': 'c', 'D': 'd'}
3. * And **
There are two special situations in the Function Definition of Python. For example, Def myfun1 (username, * keys) Or Def myfun2 (username, ** keys. * This parameter is used to pass any parameter without a name. These parameters are accessed in a tuple format. ** It is used to process and pass any parameter with a name. These parameters are accessed by dict. * Application: ######################### "*" application ######### #################>> def fun1 (* keys) :... print "keys type = % s" % type (KEYS )... print "keys = % s" % STR (KEYS )... for I in range (0, Len (KEYS )):... print "keys [" + STR (I) + "] = % s" % STR (Keys [I])... >>> fun1 (,) outputs the following results: Keys type = <type 'tuple'> keys = (2, 3, 4, 5) keys [0] = 2 keys [1] = 3 keys [2] = 4 keys [3] = 5 ################ ######### "**" application ######################## #>>> def fun2 (** keys) :... print "keys type = % s" % type (KEYS )... print "keys = % s" % STR (KEYS )... print "name = % s" % STR (Keys ['name'])... >>>>> fun2 (name = "VP", age = 19) outputs the following results: Keys type = <type 'dict '> keys = {'age': 19, 'name ': 'vps'} name = VP

4. Lambda format

For appropriate purposes, several features that are usually used in Functional Languages and lisp are added to Python. Lambda keywords allow you to create small anonymous functions. Here, a function returns the sum of two parameters: "Lambda A, B: A + B ". Lambda can be used in any function object. Due to syntax restrictions, they can only have one separate expression. In terms of semantics, they are just a syntax Technique in the definition of common functions. Similar to nested function definitions, Lambda can reference variables within the scope of inclusion:

Syntax: Lambda argument1, argument2,... argumentn:

Example 1: >>> def make_incrementor (n ):... return Lambda X: x + n...> F = make_incrementor (42)> F (0) 42> F (1) 43 Example 2: >>> F = Lambda X, Y, Z: X + Y + z> F (2, 3, 4) 9

 
5. Apply

Python provides a built-in function apply () to simplify function calling. >>> Def fun (A, B, C ):

   print a, b, c          >>> a = ("l", "M", "n")     >>> Fun(a[0], a[1], a[2])     l M n     >>> apply(Fun, a)     l M n     >>>  
6. Filter () function

The filter () function includes two parameters: function and list. This function filters out items in the list parameter based on whether the results returned by the function parameter are true, and returns a new list, as shown in the following example:

>>> A = [1, 2, 4, 5, 6, 7] >>> B = filter (lambda X: x> 5, a) >>> print B >>> [6, 7] If the filter parameter value is none, use the identity () function. All false elements in the list parameter will be deleted. As shown below: >>> A = [,] B = filter (none, A) >>>> print B >>>, 7]
7. Map () Functions

One of the two parameters of map () Is the function name, and the other is the list or tuples.

>>> Map (lambda X: x + 3, A) # A above>, 9, 10] # Another example >>> A = [, 3] >>> B = [, 6] >>>> map (lambda X, Y: x + y, a, B) >>> [5, 7, 9]

 
8. Reduce () function

The reduce function can reduce the upper sequence of input parameters to a single value according to the given method. The specific procedure is as follows: first, remove the first two elements from the sequence and pass them to the binary function to obtain a value. Then, add this element to the sequence and find the next value until the last value.

 >>>reduce(lambda x,y:x*y, [1,2,3,4,5]#((((1*2)*3)*4)*5 >>>120 >>>reduce(lambda x,y:x*y, [1,2,3], 10) >>>60 #((1*2)*3)*10

9. userstring

In python, the string is inmutable, that is, it is immutable. All C statements such as a [0] = 'A' cannot be written, but the userstring module provides this feature.

 In [1]: import UserString In [2]: a = UserString.MutableString('c'*30) In [3]: a Out[3]: 'cccccccccccccccccccccccccccccc' In [4]: a[0] = 'A' In [5]: a Out[5]: 'Accccccccccccccccccccccccccccc'

10. Python tips: determines whether two files are the same

Python provides a very convenient way to determine whether the content of the two files is the same, as long as two lines of code:

import filecmp filecmp.cmp(r'e:\1.txt',r'e:\2.txt')

If the two files are the same, true is output; otherwise, false is output.

11. dynamically generate objects

Maybe you need to dynamically generate a class instance based on specific parameters. Do you need to write a bunch of abnormal if else instances.

#!/usr/bin/env python#--*-- encoding:utf-8 --*--class MyDynamicClass:    def say_hello(self, name):        print "hello", name        def create_dynamic_cls(cls):    return globals()[cls]()a = create_dynamic_cls('MyDynamicClass')a.say_hello('Tom.')

12. @ classmethod vs @ staticmethod

  1. Class myclass :... @ classmethod # classmethod modifier def class_method (CLS, arg1, arg2 ,...) :... @ staticmethod # staticmethod modifier def static_method (arg1, arg2 ,...) :...

    13.

  2. Exefile ("filename. py ")
  3. Run the command directly on the interactive command line. All the tables are saved in a very good state and are suitable for debugging.
For the classmethod parameter, the class name needs to be passed implicitly, while the staticmethod parameter does not need to pass the class name. In fact, this is the biggest difference between the two.
Both can be called through the class name or class instance object, because the emphasis is on classmethod and staticmethod, so it is best to use the class name when writing code, good programming habits.

13.

Determines whether a list is empty.

The traditional method is: If Len (mylist): # Do something with my listelse: # The list is empty. Because an empty list is equivalent to false, you can directly: If mylist: # Do something with my listelse: # The list is empty

13. 

The traditional way to retrieve indexes while traversing the list: I = 0for element in mylist: # Do something with I and element I + = 1 is more concise: for I, element in enumerate (mylist): # Do something with I and element pass

14.

List sorting

Sorting by attribute in a list containing an element is a common operation. For example, here we first create a list containing person:

Class person (object): def _ init _ (self, age): Self. age = agejj the traditional method is: def get_sort_key (element): Return element. agefor element in sorted (persons, key = get_sort_key): Print "Age:", element. the more concise and readable method of age is to use the operator module in the python standard library: From operator import attrgetterfor element in sorted (persons, key = attrgetter ('age ')): print "Age:", element. age

attrgetterThe method first returns the read property value as a parameter and passes itsortedMethod.operatorThe module also includesitemgetterAndmethodcallerMethod, as its literal meaning.

15. element grouping in dictionary

Like above, create persons first:

class Person(object):    def __init__(self, age):        self.age = agepersons = [Person(age) for age in (78, 14, 78, 42, 14)]

If we want to group by age, one way is to use the in OPERATOR:

persons_by_age = {}for person in persons:    age = person.age    if age in persons_by_age:        persons_by_age[age].append(person)    else:        persons_by_age[age] = [person]assert len(persons_by_age[78]) == 2

In comparison, the defaultdict method in the collections module is more readable:

from collections import defaultdictpersons_by_age = defaultdict(list)for person in persons:    persons_by_age[person.age].append(person)

Defaultdict will use the accepted parameters to create a corresponding value for each nonexistent key. Here we pass the list, so it will create a value of the list type for each key.

16: List comprehethion

>>> [i for i in a if i % 2 == 0][2, 4, 6]>>> [i * i for i in a if i % 2 == 0][4, 16, 36]>>> {i * i: 1 for i in a if i % 2 == 0}{16: 1, 36: 1, 4: 1}

17. Check whether the string is another string.

string = 'Hi there' # True example2# string = 'Good bye' # False example3if 'Hi' in string:4    print 'Success!'

18 reload Test

import test
>>> test.answer_to_life_the_universe_and_everything54>>> # Whoops that's not right, I'd better edit the module.......>>> reload(test)>>> test.answer_to_life_the_universe_and_everything

19 pading

>>> n = '4'>>> print n.zfill(3)>>> '004'And for numbers:>>> n = 4>>> print '%03d' % n>>> '004'

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.