Python tips (5)

Source: Internet
Author: User

1. List sequence, sample_list = [1, 2, 3, 'abc']

Dictionary dictionary, sample_dic = {"key" = value, 2: 3}

Tuple read-only sequence, sample_tuple = (1, 3, "AB ")

Sequence Table: a sequence table is composed of a series of values separated by commas. The sequence table is not variable like a string, and a value assignment to a sequence table is not allowed.

Dictionary: Associate an array.

Unlike strings, the list is variable. You can modify each element of the list. You can create a nested list (the table element is also a list ).

 

2. built-in functions:

Filter (), filter (function, sequence) returns a sequence (as much as possible with the original type), when the sequence elements are filtered by the specified function in the original sequence, the filter rule is "function (sequence element) = true". Filter () can be used to retrieve a subset that meets the conditions.

Map (), map (function, sequence) calls the specified function for each item of the specified sequence, and the result is a list of returned values. Map () can perform an implicit loop on the sequence.

Reduce (), reduce (function, sequence) is used to perform operations such as accumulate. The function here is a function of two sub-variables, reduce () first, call the first two functions of the sequence to get a result. Then, call the function of the result and the next function of the sequence to get a new result.

 

3. The and Expression in python is calculated from left to right. If all values are true, the last value is returned. If false exists, the first value is returned.

Or is also a left-to-right expression, and returns the first true value.

>>> 'a' and 'b''b'>>> '' and 'b'''>>> 'a' or 'b''a'>>> '' or 'b''b'

In addition, there is a usage similar to the three-object expression: bool? A: B

A = 'first 'B = 'second' print 1 and A or B # is equivalent to the case where bool = True Print 0 and A or B # is equivalent to the case where bool = false A = ''print 1 and A or B # When a is false, print (1 and [a] or [B]) [0] # Security usage, because [a] cannot be false, at least one element >>> firstsecondsecond >>>

Another example.

collapse = True # FalseprocessFunc = collapse and (lambda s:" ".join(s.split())) or (lambda s:s)

There is no problem here, because a Lambda function is always true in a Boolean environment. (This does not mean that the lambda function cannot return a false value. The function itself is always true, and its return value can be any value ).

test = lambda x, y, z = 2:x*y*zprint test(2, 3, 4)print test(2, 3)>>> 2412>>> 

Note that Lambda is an optional parameter. A Lambda function is just an inline function.

 

4. You can use reverse () in reverse sequence ().

 

5. How does one convert tuple and list in Python?

1) The function tuple (SEQ) can convert all iteratable (iterable) sequences into a tuple. The elements remain unchanged and the sorting remains unchanged.

E.g. tuple ([1, 2, 3]) returns (1, 2, 3)

Tuple ('abc') returns ('A', 'B', 'C ')

If the parameter is already a tuple, the function directly returns the original object without any copy. Therefore, it is not very expensive to call the tuple () function when you are not sure whether the object is a tuple.

2) The list (SEQ) function can convert all sequences and iteratable objects into a list. The elements remain unchanged and the sorting remains unchanged.

For example, list ([1, 2, 3]) returns (1, 2, 3), list ('abc') Returns ['A', 'B ', 'C']. If the parameter is a list, it will make a copy like set.

 

6. Write a piece of Python code to delete repeated elements in a list.

def del_Redundant(seq):    for item in seq:        if seq.count(item) > 1:            del seq[seq.index(item)]    return seqprint del_Redundant([1, 2, 3, 4, 1, 5, 2, 6, 1])>>> [3, 4, 5, 2, 6, 1]>>> 

7. How to copy an object in Python:

In python, no matter the object is passed as a parameter or as a function return value, it is passed by reference.

The copy module in the Standard Library provides two methods for copying. One method is copy, which returns objects with the same content as parameters.

import copynew_list = copy.copy(existing_list)

If you want to copy the attributes of an object, you can use the deepcopy method.

import copynew_list_of_dics = copy.deepcopy(existing_list_of_dicts)

Copy. Copy can be used for shallow copy. References are still used for the elements in the object.

In light replication, you sometimes cannot get a copy that is exactly the same as the original object. If you want to modify the elements in an object, not just the object itself.

>>> [3, 4, 5, 2, 6, 1]>>> import copy>>> list_of_lists = [['a'], [1, 2], ['z', 23]]>>> copy_lol = copy.copy(list_of_lists)>>> copy_lol[1].append('boo')>>> print list_of_lists, copy_lol[['a'], [1, 2, 'boo'], ['z', 23]] [['a'], [1, 2, 'boo'], ['z', 23]]>>> a = [1, 2, 3]>>> b = a>>> b.append(5)>>> print a, b[1, 2, 3, 5] [1, 2, 3, 5]>>> s = 'cat'>>> t = copy.copy(s)>>> s is tTrue>>> 

Note that the T = Copy. Copy (s) sentence cannot be modified (string, number, tuples), and the original object will still be obtained by copying.

The is operator is used to determine whether two objects are completely consistent and are the same object.

Objects in Python contain three elements: ID, type, and value.

ID is used to uniquely identify an object. Type identifies the object type. value is the object value.

Is determines whether object A is a B object and is determined by ID.

= Determines whether the value of object A is equal to the value of object B. It is determined by value. See the following code.

>>> a = 1>>> b = 1.0>>> a is bFalse>>> a == bTrue>>> id(a)27047920>>> id(b)27080240>>> a = 1>>> b = 1>>> a is bTrue>>> a == bTrue>>> id(a)27047920>>> id(b)27047920>>> #dictionary>>> a = {'m':1, 'n':2}>>> b = dict(a)>>> a is bFalse>>> a == bTrue>>> #list>>> a = [1, 2, 3]>>> b = list(a)>>> a is bFalse>>> a == bTrue>>> #tuple>>> a = (1, 2, 3)>>> b = tuple(a)>>> a is bTrue>>> a == bTrue>>> 

8. Role of the pass statement in Python:

1) The pass statement does not do anything. It is generally used as a placeholder or creates a placeholder program. The pass statement does not perform any operations.

while False:    pass

2) The pass statement is usually used to create the simplest class.

class MyEmptyClass:    pass

3) Pass is often used as a todo in the software design stage to remind you to implement the corresponding functions.

def initlog():    pass # please implement this

9. Python exception handling.

class myException(Exception):    def __init__(self, str):        Exception.__init__(self, str)        self.value = strtry:    raise myException("error...")except myException, e:    print e.valuefinally:    print "pass">>> error...pass>>> 
try:    raise Exception, "hello world"except Exception, e:    print e>>> hello world>>> 

10. Python assert usage:
1) The assert statement is used to declare that a condition is true.

2) if you are very sure that a list of users has at least one element and want to check this, and an error is thrown when it is not true, it is more suitable to use assert statements.

3) when the assert statement fails, an assertion error is triggered.

>>> my_list = ['item']>>> assert len(my_list) >= 1>>> my_list.pop()'item'>>> assert len(my_list) >= 1Traceback (most recent call last):  File "<pyshell#52>", line 1, in <module>    assert len(my_list) >= 1AssertionError>>> 

11. Type (X) is used to understand the type of a python object ).

 

12. Use range in Python.

1) range (STOP)

2) range (start, stop [, step])

>>> range(10)[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>> range(1, 11)[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]>>> range(0, 30, 5)[0, 5, 10, 15, 20, 25]>>> range(0, 10, 3)[0, 3, 6, 9]>>> range(0, -10, -1)[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]>>> range(0)[]>>> range(1, 0)[]>>> 

13. Python global variables:

def a():    x = 2    print xdef b():    global x    x = 4    print xx = 3print xa()print xb()print x>>> 32344>>> 

1) global variable global variables:
Can be referenced anywhere in the program file, including the internal functions and classes. However, if you assign values to global variables in functions and classes, the variable must be declared as a global variable in the function or class. Otherwise, the variable is a local variable after being assigned a value.

2) local variable local variables:

It is usually used directly in a function or class method. It cannot be referenced outside of the function or class method.

 

14. Generate a random number in Python:

Import randomrandom. random () # [0.0, 1.0) a floating point random. randint (start, stop) # an integer random in [start, stop. randrange (start, stop) # an integer in [start, stop)

15. Regular Expressions are usually used to search for matched strings in the text.

The process of matching using a regular expression:

First, the Regular Expression Engine compiles the regular expression text to generate a regular expression object (including information on how to perform matching ), then match the regular expression object with the text to be matched to obtain the matching result (including the information of the successful match, such as the matched string, group, and index in the text ).

 

16. Use python to query and replace a text string.

import repattern = re.compile('blue|white|red')print pattern.sub('haha', 'blue socks and red shoes')print pattern.sub('haha', 'blue socks and red shoes', 1)print pattern.subn('haha', 'blue socks and red shoes')print pattern.subn('haha', 'blue socks and red shoes', 1)>>> haha socks and haha shoeshaha socks and red shoes('haha socks and haha shoes', 2)('haha socks and red shoes', 1)>>> 

17. Differences between search () and match () in Python.

1) The match () function only checks whether the re matches at the starting position of the string. Search () scans the entire string for matching, that is, match () only when the 0-position match is successful is returned. If the start position match is not successful, match () returns none.

2) Search () scans the entire string and returns the first successful match.

import reprint re.match('super', 'superstition').span()print re.match('super', 'superstition')print re.match('super', 'insuperable')print re.search('super', 'superstition').span()print re.search('super', 'superstition')print re.search('super', 'insuperable').span()print re.search('super', 'insuperable')>>> (0, 5)<_sre.SRE_Match object at 0x015E1D40>None(0, 5)<_sre.SRE_Match object at 0x015E1D40>(2, 7)<_sre.SRE_Match object at 0x015E1D40>>>> 

18. When Python matches an HTML Tag, <. *> and <. *?> What is the difference?

1) <. *> greedy match

2) <. *?> Non-Greedy match

import res = 'abc'print re.match('.*', s).group()print re.match('.*?', s).group()print re.match('a.*', s).group()print re.match('a.*?', s).group()>>> abcabca>>> 

19. How do I send emails in Python?

You can use the smtplib standard library.

The code can be executed on a server that supports SMTP listeners.

 

20. Is there a tool that can help you find Python bugs and perform static code analysis?

1) Yes. pychecker is a static analysis tool for Python code. It can help you find bugs in Python code and warn you about the complexity and format of the Code.

2) pylint is another tool that can perform the coding standard check.

 

21. How does Python perform memory management?

Python memory management is the responsibility of the python interpreter. developers can free up from the memory manager transactions and devote themselves to application development. This reduces program errors, the program is more robust and the development cycle is shorter.

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.