The derivation of Python lists, collections, and dictionaries __python

Source: Internet
Author: User

1, the basic derivation type

(1) List derivation is one of the most popular features of Python, and it can be used to construct new lists very efficiently: just a simple piece of code that filters the family elements and distorts the resulting elements with the following basic grammatical structure:

[Exp for Val in collection if condition] #列表推导式

The code above corresponds to the following loop:

result = []
   ...: For Val in collection:
   ...:     if condition:
   ...:         result.append (val)

The condition of the filter can be omitted, leaving only an expression. As a list of strings given below, filter out strings that are less than 2 long and convert the string to uppercase:

In [8]: STRs = [' py ', ' tuple ', ' list ', ' Python ', ' P ', ' Pip '] in

[9]: [Str.upper () for STR in STRs if Len (str) >2]
  
   OUT[9]: [' TUPLE ', ' LIST ', ' PYTHON ', ' PIP ']
  

(2) The derivation of the set and the dictionary is a natural continuation of the idea, and they are similar in syntax, resulting in collections and fields. The grammatical form of the dictionary derivation is as follows:

Dict_comp = {key-expr:value-expr for value in collection if condition}

A collection derivation is very similar to a list derivation, except that it uses curly braces (curly braces) instead of brackets (square brackets), as follows:

Set_comp = {expr for value in collection if condition}

Here's an example of collection derivation and dictionary derivation:

In [one]: STRs = [' py ', ' tuple ', ' list ', ' Python ', ' P ', ' Pip '] in

[[]: {len (str) for STR in STRs}
out[12]: {1, 2, 3 , 4, 5, 6} in

[[n]: #字段推导式 in

[n]: loc_mapping = {value:idx for IDX, value in Enumerate (STRs)}

: Loc_m Apping
out[15]: {' Pip ': 5, ' list ': 2, ' P ': 4, ' py ': 0, ' Python ': 3, ' tuple ': 1}

For dictionary derivations, there is another way:

in [[]: Loc_mapping2 = Dict ((value,idx) for IDX, value in enumerate (STRs)) in

[]: Loc_mapping2
out[17]: {' Pip ': 5, ' list ': 2, ' P ': 4, ' py ': 0, ' Python ': 3, ' tuple ': 1}

2, the derivation of nested list

Let's look at the following example:

in [[]: Name_all = [[' Qqing ', ' wqing ', ' Qinggo ', ' ewv ', ' wqc '],[' list ', ' listqq ', ' tep ', ' SDK ', ' Pqrst '] ', '
[]: qqs= [] in

[[]: For name in Name_all:
    ...: qq=[n for     N in Name if N.count (' Q ') >=2]
    ...:     qqs.extend (QQ)
    ...:

in [[]: Qqs
out[23]: [' qqing ', ' listqq ']

again, the derivation of the nested list is implemented in a more concise way:

In [to]: Qqs2=[n for name in Name_all to N in name if N.count (' Q ') >=2] in

[n]: Qqs2
out[26]: [' qqing ', ' lis Tqq ']

At first glance, the derivation of the nested list is not good, in fact the part of the derivation for is in the nesting order, and the filter condition is the same as before. Here is another example of "flattening" a list of string tuples into a simple list of strings:

in [[]: Lstr =  [(' Java ', ' Python ', ' C + + '), (' for ', ' while ', ' Do...while '), (' in ', ' isnull ', ' NOT NULL ')] in

[28]: result = [x for tu in lstr for x in Tu] in

[[]: Result
out[29]:
[' java ',
 ' python ',
 ' C + + '
 , ' for ',
 ' while ',
 ' do...while ',
 ' in ',
 ' isnull ',
 ' not NULL '

A much easier way to understand memory is how the order of each for in the nested for loop is, and what the order of each for expression in the nested derivation is.

It should also be noted that the syntax in the example above is not the same as " list derivation in list derivation ", as the following example syntax is correct, but the result is different:

In [m]: RESULT2 = [[x for X in Tu] for tu in lstr] in

[to]: Result2
out[31]:
[[' Java ', ' Python ', ' C + + '],
  [' for ', ' while ', ' Do...while '],
 [' in ', ' isnull ', ' NOT NULL ']]
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.