Learning Log---Python (list parsing, generators, dictionaries, and collections)

Source: Internet
Author: User
Tags set set

The resulting list can be used with range ();

List parsing

A new list is generated for parsing a sequence, and the list parsing is much better than for performance;

A=[x for x in range (0,10) if x > 5]print aa=[x+1 for x in range (0,10) if x > 5]print A

Use the expressions in the list to get the list you want, without having to use a for loop;

Double nesting: Use simpler statements to get a list:

a=[(x, y) for x in range (3) for Y in range (3)]print a

There are a number of built-in functions available in the parser:

Filter (Function,iter)

Fuction is a function that accepts only one parameter, that is, the sequence of ITER that is passed in, and returns a filtered sequence;

The returned value is the value in ITER, which satisfies the return, fuction is true;

Map (Function,iter)

Functions are a function that takes all the elements of the ITER list in turn, generating a list of the corresponding return values;

def f (x): Return x%5==0def U (x): Return x+1a = Filter (F,range (0,100)) Print AA = Map (U,range (0,10)) print a

The disadvantage of list parsing is that memory efficiency is too low;


Builder expression

Each time only one element is loaded and returned, the only syntax that is different from the list parsing is the parentheses , which returns a list header pointer

, when the pointer is obtained, it needs to be obtained by the For loop;

A = (x for x in range (0,10) if x%3==0) print afor i in A:print i

Condition is not 0 o'clock, that is, the element to be returned is 0 o'clock, or false


Xrange

The generator version of range, with a wide range of requirements, with this; As with the use of range

For I in Xrange (0,9999999): If I%999==0:print I


Dictionaries and collections

Dictionary

Dictionary is an unordered key-value pair, based on the implementation of a hash table, key can be hash, hash function to calculate the value, and then the value;

Types that can be built (content is immutable):

The general recommendation is to use a string; class instance to do key, you need to implement hash method return hash value, list and dictionary can not do key, because list and dictionary variable; tuples can do key, cannot contain list inside. ;

The built-in hash () function can be used to determine whether it can be used as a key value;

Create a dictionary: {key:value}, or you can use the Dict () factory function to create

A={' A ': 1, ' B ': 2}print aa=dict (a= ' C ', b=2) print Aprint a.get (' C ', ' not exist ')

Dict () function is created so that the key is the default string, value is also the default, the number can be directly written;

In the dictionary does not confirm whether there is a key, you can use the dictionary get method to fetch, no error, return the default value, this is a very safe operation;

Del Dict[key] can be deleted, dict[' None ']=3, if the key is not, then create;

Find key:

The Keys function returns a list of keys that exist in the dictionary.

A={' A ': 1, ' B ': 2, ' C ': 3}b = A.keys () Print B


Collection (SET)

A = set ([+]) b = List ([1,2,3,4]) B.append (5) A.add (5)

The value inside the set set is unique, adding the element with the Add method, update updates a set of sequences at the same time;

A collection can be federated, intersect, set, and XOR.


Topic:

Design a function zip (LISTA,LISTB,REPL), enter two lists and placeholders, return a new list, each element of the list is a tuple, the elements of the tuple are the same order in the Lista and LISTB elements, if the length is not the same, use placeholders instead.

Def zip (LISTA,LISTB,REPL):     lena = len (lista)     lenb  = len (LISTB)     length = 0    list = []     if lena < lenb:         Length = lena    else:        length  = lenb    for i in range (0,length):         list.append ((lista[i],listb[i))     if lena >  Length:        for i in range (Length,lena):             list.append ((LISTA[I],REPL))      if lenb > length:        for i in  range (LENGTH,LENB): &NBSP;&NBsp;          list.append ((repl,listb[i))      print listzip ([1,2,3],[4,5,6], "a") zip ([1,2,3],[4], "B")



Learning Log---Python (list parsing, generators, dictionaries, and collections)

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.