Python Basics 5 (collections, advanced features, higher-order functions)

Source: Internet
Author: User
Tags iterable

650) this.width=650; "src=" Https://s4.51cto.com/wyfs02/M01/06/2C/wKiom1myzQrAksneAAIAo4q9Ahw439.png "title=" Wkiol1mmt57qsthaaaiaoam4qco995.png "alt=" Wkiom1myzqraksneaaiao4q9ahw439.png "/>



* * Remove duplicate elements from the list: L = [1,2,3,1,2,3]

-Mandatory conversion list for collection type: List (set (L))

-Convert the list to a dictionary and take out all the key values inside: Dict.fromkeys (L). Keys ()

* * Two ways to implement switch:

-If...elif...else ...

-Implemented by dictionary: d= {"Key", Func}

If Oper in D.keys ():

D[oper] ()

Else

Print "Error"

# Collection

# # Introduction of the collection:

Community

Linux Interest Group LINUXL = ["Wang Weber", "Wang Jianqiang"]

Python interest Group pythonl = ["Wang Weber", "Huangxin"]

。。。。

-Statistics of all associations L = []

-student = "Wang Weber"

-List: LINUXL + pythonl = ["Wang Weber", "Wang Jianqiang", "Wang Weber", "Huangxin"]

-Collection: {"Wang Jianqiang", "Wang Weber", "Huangxin"}

-ACM Competition:


# # Definition of the collection

* * Immutable data types must be hashed; a hash () built-in function can determine whether a type can be hashed;

# # Set of relationship tests

```

S1 = {1, 2, 3}

S2 = {2, 3, 4}

S3 = {1, 2}

S4 = {5}

Print "Intersection of S1,S2,S3:", s1.intersection (S2, S3)

Print "S1,s2,s3 intersection:", S1 & S2 & S3

Print "S1,S2,S3:", s1.union (S2, S3)

"S1,s2,s3 of print": ", S1 | S2 | S3

Print "S1-s2 of Difference:", s1.difference (S2)

Print "S1-s2 of Difference:", s1-s2

Print "S1-s2-s3 of Difference:", s1.difference (S2, S3)

Print "S1-s2-s3 of Difference:", S1-S2-S3

Print "S2-s1 of Difference:", s2.difference (S1)

print "S1 and S2 equivalent differential:", s1.symmetric_difference (S2)

print "S1 and S2 equivalent differential:", S1 ^ s2

print "S2 and S1 equivalent differential:", S2.symmetric_difference (S1)

# s.isdisjoint (S2) If there is an intersection, return false; otherwise, return true;

Print "S1 and S4 No intersection:", S1.isdisjoint (S4)

Print "S3 is a subset of S1:", S3.issubset (S1)

Print "S1 is the parent set of S3:", S1.issuperset (S3)

```

# # Collection of additions and deletions to search:

-Added: S.add (1), s.update (S1)

Delete

S.remove (1), # Delete existing element, if not present, direct error;

S.discard (1) # Delete the existing element if it does not exist, do nothing;

S.pop (), # Deletes the collection element without adding any parameters;

-copy: S1 = s.copy () #s和s1的id不同

-Empty: S.clear ()

# Frozen Set (Frozenset)

-Freeze the set, can not be deleted or modified;

-Frozenset (SET)

-Set (Frozenset)

# Advanced Features

# # Slice

# # Iterations

-any object that can be iterated can be traversed with a for loop;

-Iteration of the dictionary: The default is to iterate through key;

For I in D:

Print I

-Enumeration of dictionaries: enumerations can only return two values, one is index subscript, and the other is an iterative element;

D = {1: "A", 2: "B"}

For i,j in Enumerate (d):

Print I,j,d[j]

-How to determine if it is possible to iterate

From collections Import iterable

Isinstance ("Hello", iterable)

# # List-generated

List generation, in fact, is a way to generate a list, is Python built-in;

-Simple List-generation

[I*i for I in range (10)]# returns a list of 1-10 squares;

[Fun (i) for I in l]# performs a function operation on each element of the list;

-Nesting of For...if

[I*i for I in range (1,10) if i%2==0]# returns all the even numbers between 1-10

[I for I in range (1,10) if IsPrime (i)]# returns all prime numbers between 1-10, the function that determines prime numbers is custom;

-For...for ... The nested

[I+j for I in ' ABC ' for j in "123"]# returns all combinations of "abc" and "123";

# # Generator

-List generation can create a list directly, but the list capacity is limited by memory;

-The mechanism of looping one side in Python, called the Generator (Generator), is how much you need and how much it generates;

# # # Methods for creating generators:

-Change the list-generated [] to ();

-Add the yield keyword to the defined function;

# # # How to view builder elements:

-Use the next method of the generator; (infrequently used)

-The generator is an iterative object that is viewed directly through a for loop;

1, 1,

max = 6

def fib (max):

N,a,b = 0,1,1

While n < 6:

Print a

A, B = C, a + b

n = n + 1

# higher-order functions

# # Built-in high-order functions

-Map

-Reduce

Reduce (f,[1,2,3,4]) = = = > Add (add), 3, 4)

Reduce (Cheng,range (1,11))

* * for factorial of 10:

-Filter

in [+]: def is_oushu (n):

....: if n%2 = = 0:

....: Return True

.....: Else:

....: Return False

....:

in [+]: Filter (Is_oushu,range (1,11))

OUT[16]: [2, 4, 6, 8, 10]

-Sorted ()

```

n []: L = ["A", "Ab", "CD", "C"]

in [+]: sorted (L)

OUT[21]: [' Ab ', ' C ', ' A ', ' CD ']

In []: def cmp_ignore_case (S1,S2):

.....: S1 = S1.lower ()

.....: S2 = s2.lower ()

....: If S1 < s2:

.....: return-1

....: elif S1 > S2:

....: return 1

.....: Else:

....: return 0

....:

In [23°c]: sorted (l,cmp_ignore_case)

OUT[23]: [' A ', ' Ab ', ' C ', ' CD ']


This article is from the "13122425" blog, please be sure to keep this source http://13132425.blog.51cto.com/13122425/1963855

Python Basics 5 (collections, advanced features, higher-order functions)

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.