Python learning diary (Week 4), python Week 4

Source: Internet
Author: User
Tags new set union of sets

Python learning diary (Week 4), python Week 4
Set Data Type

Use a line of code to describe

#!/usr/bin/env pythons2={}s = {33,12,33,32121}for i in s:    print(i)print(type(s))print(type(s2))s1=set()s1.add(11)s1.add(22)s1.add(33)print(s1)

The running result of the following code

321211233<class 'set'><class 'dict'>{33, 11, 22}

The code result shows that

  • Set is an unordered and non-repeating element set.
  • Identical set and dictionary creation {} Only internal elements can reflect the difference
  • To create an empty set, you 'd better use the set () method to create it, and then add the element through the add method.

The following are some common methods of set collection:

Class set (object): "set ()-> new empty set object set (iterable)-> new set object Build an unordered collection of unique elements. "def add (self, * args, ** kwargs): # real signature unknown" "Add an element to a set, add the element This has no effect if the element is already present. "pass def clear (self, * args, ** kwargs): # real signature unknown" Remove all elements from this set. clear content "" pass def copy (self, * args, ** kwargs): # real signature unknown "" Return a shallow copy of a set. shallow copy "" pass def difference (self, * args, ** kwargs): # real signature unknown "" Return the difference of two or more sets as a new set. A exists, B does not exist (I. e. all elements that are in this set but not the others .) "" pass def difference_update (self, * args, ** kwargs): # real signature unknown "Remove all elements of another set from this set. delete the same element "" pass def discard (self, * args, ** kwargs) from the current set as B ): # real signature unknown "Remove an element from a set if it is a member. if the element is not a member, do nothing. remove the specified element. The error "pass def intersection (self, * args, ** kwargs) does not exist ): # real signature unknown "" Return the intersection of two sets as a new set. intersection (I. e. all elements that are in both sets .) "" pass def intersection_update (self, * args, ** kwargs): # real signature unknown "Update a set with the intersection of itself and another. take the intersection and update it to "pass def isdisjoint (self, * args, ** kwargs ): # real signature unknown "" Return True if two sets have a null intersection. if no intersection exists, True is returned. Otherwise, False "pass def issubset (self, * args, ** kwargs) is returned ): # real signature unknown "Report whether another set contains this set. whether the subsequence "pass def issuperset (self, * args, ** kwargs): # real signature unknown" Report whether this set contains another set. whether the parent sequence "pass def pop (self, * args, ** kwargs): # real signature unknown" Remove and return an arbitrary set element. raises KeyError if the set is empty. remove element "" pass def Remove (self, * args, ** kwargs): # real signature unknown "remove an element from a set; it must be a member. if the element is not a member, raise a KeyError. remove the specified element. The error "pass def into ric_difference (self, * args, ** kwargs) does not exist ): # real signature unknown "" Return the specified Ric difference of two sets as a new set. symmetric Difference set (I. e. all elements that are in exactly one of the sets .) "pass def into ric_difference_update (self, * args, ** kwargs): # real signature unknown" Update a set with the specified Ric difference of itself and another. symmetric Difference set, and updated to "pass def union (self, * args, ** kwargs) in ): # real signature unknown "" Return the union of sets as a new set. union (I. e. all elements that are in either set .) "pass def update (self, * args, ** kwargs): # real signature unknown" "Update a set with the union of itself and others. update "" pass
Ternary Computation

Triplicate (triplicate) is short for simple conditional statements.

 

# Writing format result = value 1 if condition else value 2 # if the condition is true, assign "value 1" to the result variable. Otherwise, assign "value 2" to the result variable.
Supplement of condition judgment

When condition 1 or condition 2 and Condition 3 exist in the if statement

Executed in order. when conditions are met, they are not found.

Therefore, you must change it to (condition 1 or condition 2) and Condition 3.

Depth copy description

In the following Environments

When the memory address is found, the data content is considered to be found.

For numbers and strings

Variable ========= house name

Memory Address (actual data) ===== house address

Assignment ========= house name-house address

Memory ========= intermediary (with many listings)

Shortest copy

View house address list

The shortest copy and deep copy are meaningless because they always point to the same memory address. (House address)

For dictionaries, ancestor, and list

Dictionary, ancestor, list is equivalent to a house with many rooms inside the house

House = [room number, room number, room number]

Therefore, the set of room numbers of the dictionary, yuanzu, and list-store houses === house room numbers

For a shortest copy

It is equivalent to copying a house room number table.

For deep copy

Build a room according to the room number table

Note !! Python optimizes strings and numbers internally, so the last layer (based on the house room number table) points to the same address.

It can be understood

Deep copy: Creates a new copy of all data in the memory (excluding the last layer, namely, optimizing strings and numbers in python)

Function

The purpose of a function or method is to integrate a large number of repeated code in the program to make the program more concise and understandable.

The most important thing in functional programming is to enhance code reusability and readability.

Function Definition
Def function name (parameter):... function body... return value

Function Definition is defined using the def keyword + function name

Functions are defined as follows:
  • Def: indicates the function keyword.
  • Function Name: name of the function. The function will be called Based on the function name in the future.
  • Function body: perform a series of logical calculations in the function, such as sending emails and calculating the maximum number in [11, 22, 38,888, 2...
  • Parameter: provides data for the function body.
  • Return Value: After the function is executed, the caller can return data.

Built-in functions

Function return value

A function is a function block. Whether the function is successfully executed or not, the caller must be informed of the returned value.

For example:

#! /Usr/bin/env pythondef funcl (): return "The program executes" r = funcl () print (r)

The return value can be a string or another data type.

By default, return returns None:

Note: The code below return will not be executed again

Function Parameters

When defining a function, we can determine the parameter name and position, and define the function interface. For a function caller, you only need to know how to pass the correct parameters and what values the function will return. The complex logic inside the function is encapsulated, And the caller does not need to know.

The parameter of a function is to give the function an internal data so that the internal code can be repeatedly executed and different results can be generated for reuse.


For example, calculate the number of records of x

def power(x):    return x * x
>>> power(5)25>>> power(15)225

You can change the value of x to obtain the number of shards of any number.

There are three types of function parameters

  • Common parameters, such as x in the preceding example
  • Default parameters
  • Dynamic Parameters
Default parameters

The default parameter is a default value.

For example

#!/usr/bin/env pythondef power(x):    return x * xpower()

When the value of x is given, the program reports an error.

Traceback (most recent call last):  File "C:/Users/zhang/PycharmProjects/untitled/blog.py", line 4, in <module>    power()TypeError: power() missing 1 required positional argument: 'x'

Modify the program

#!/usr/bin/env pythondef power(x=0):    return x * xr =print(power())

In this way, even if the x value is not given, the program has a default value. Therefore, the program runs normally.

Dynamic Parameters

Function parameters can be not only a variable, but also a list or dictionary.

Def func (* args): print args # execution method 1 func (11,33, 4454, 5) # execution method 2 li = [11,2, 54] func (* li) Dynamic Parameters
Def func (** kwargs): print args # execution method 1 func (name = 'wupeiqi ', age = 18) # execution method 2 li = {'name ': 'wupeiqi ', age: 18, 'gender': 'male'} func (** li) Dynamic Parameters

 

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.