Python3 entry learning one.md

[ TOC]

1. A brief introduction to Python3###

The 3.0 version of Python is often called Python 3000, or Py3k for short.

The breadth of the Python language:

2. Python3 installation###

Install Python3 command in Linux, download https://www.python.org/downloads/source/ on the official website

tar -zxvf Python-3.6.1.tgz
cd Python-3.6.1./configure
make && make install
python3 -V

ipython is a python interactive shell (i stands for interaction). It is much easier to use than the default python shell. It supports automatic variable completion, automatic indentation, and bash shell commands. It has many useful functions and built-in function.

The Linux environment can also be installed using the following command:
pip install ipython
sudo apt-get install ipython #Ubuntu
yum install ipython  #c entos

Environment variable configuration:
setenv PATH "$PATH:/usr/local/bin/python"//csh shellexport PATH="$PATH:/usr/local/bin/python"// bash shell (Linux)enter
PATH="$PATH:/usr/local/bin/python"//Type in sh or ksh shell:
path=%path%;C:\Python   //Set environment variables in Windows:

Python environment variables:

Python environment traversal

Three modes of running Python

The following are the Python command line parameters:

Python command line parameters

3. Comparison between Python3 and Python2.X###

# Py2
print a 

# py3
print(a)
>>> a =1024>>> b ="weiyigeek">>>print( b + a)   #3.x
>>> print b + a     #2.x
# Will report an error, the solution
>>> print b +`a`  #2.x  
Weiyigeek1024        #Actually repr and``Is consistent enough to convert the resulting string into a legal Python expression;>>>print( b +repr(a))   #3.x Same as above
>>> print( b +str(a))   #3.x
>>> name =raw_input("please enter your name:")  #2.x
Please enter your name: WeiyiGeek
>>> print(name)
WeiyiGeek
# cmp(String,String)Or cmp(int,int) 比较String和整形
>>> cmp(1,2)   #The former is smaller than the latter-1-1>>>cmp("abc","abb")  #The former is greater than the latter returns 11>>>cmp("abc","abc")  #The former is equal to the latter returns 00
# Method 1; statement at the beginning of the file
# - *- coding:utf-8-*-

# Method 2:
unicode_str =unicode('Chinese',encoding="utf-8");
print unicode_str.encode('utf-8');

# Method 3: Open the file using codes.open instead of open function;
import codecs
codecs.open('filename',encoding='utf-8');

supplement:

# It is easy to report errors when the code set is not specified
UnicodeDecodeError:'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128)'

# It is found that it is an ascii coding problem. Add the following sentences in front of your program code to solve the problem:
import sys
reload(sys)
sys.setdefaultencoding('gb18030')
# Python3 - encode
>>>" I am a cyber security practitioner".encode('utf-8')
b'\xe6\x88\x91\xe6\x98\xaf\xe4\xb8\x80\xe4\xb8\xaa\xe7\xbd\x91\xe7\xbb\x9c\xe5\xae\x89\xe5\x85\xa8\xe4\xbb\x8e\xe4\xb8\x9a\xe8\x80\x85'>>>"I am a cyber security practitioner".encode('gbk')
b'\xce\xd2\xca\xc7\xd2\xbb\xb8\xf6\xcd\xf8\xc2\xe7\xb0\xb2\xc8\xab\xb4\xd3\xd2\xb5\xd5\xdf'

# Python3 - decode 
se.decode('gbk')'I am a cyber security practitioner'>>> b'\xe6\x88\x91\xe6\x98\xaf\xe4\xb8\x80\xe4\xb8\xaa\xe7\xbd\x91\xe7\xbb\x9c\xe5\xae\x89\xe5\x85\xa8\xe4\xbb\x8e\xe4\xb8\x9a\xe8\x80\x85'.decode('utf-8')'I am a cyber security practitioner'
# The difference between mysql package
py2:pip install mysql-python
py3:pip install mysqlclient

4. Python3 basic syntax###

4.1 Python Chinese coding####

The default encoding format in Python is ASCII format. Chinese characters cannot be printed correctly when the encoding format is not modified. Therefore, when reading Chinese, an error will be reported. All codes contain Chinese, so you need to specify the encoding in the header.
Case 1: The first Python program Hello Wrold:

# Solution: Just add at the beginning of the file# -*- coding: UTF-8-*-or#coding=utf-8 will do
#! /usr/bin/python3
# coding=utf-8
# - *- coding: UTF-8-*-
# - *- coding: cp936 -*-print("Hello World, Python 3.x!only")print("Hello world");

Python Chinese encoding

Precautions:
Python3.X source code files use utf-8 encoding by default, so Chinese can be parsed normally without specifying UTF-8 encoding, but you need to set the format of py file storage to UTF-8 during development, otherwise it will appear Similar to the following error message

4.2 Python basic grammar learning

In Python, all identifiers can include English, numbers, and underscores (_), but cannot start with a number, and identifiers are case sensitive;

Single underline: single underline_Class attributes that cannot be directly accessed at the beginning of foo must be accessed through the interface provided by the class,Cannot use from xxx import*Import.
Double underscore: beginning with a double underscore__foo stands for private members of the class, beginning and ending with a double underscore__foo__Represents an identifier dedicated to a special method in Python, such as__init__()Represents the constructor of the class.

**Python variable definition: **
Variables in Python do not need to be declared, each variable must be assigned before use, and the variable will be created after the variable is assigned;
Since Python is a weakly typed language, the type belongs to the object, and the variable has no type. The variable is just a reference to an object (a pointer), and a variable can point to different types of objects by assignment, such as:
The left side of the equal sign (=) operator is a variable name, and the right side of the equal sign (=) operator is the value stored in the variable. Python allows you to assign values to multiple variables at the same time; when you specify a value, the Number object will Is created, you can use del statement to delete some object references;

a=[1,2,3]
a="Runoob"
# In the above code,[1,2,3]Is of type List,"Runoob"Is of String type, and the variable a has no type, she just
# It is a reference to an object (a pointer), which can point to either a List type object or a String type object.

In python, strings, tuples, and numbers are unchangeable objects, while list, dict, and set are changeable objects.

Case: Python variable assignment:

#! /usr/bin/python3
# - *- coding:UTF-8-*-
# Function: definition and use of variables

int1 =23
float1 =100.0
string ="WeiyiGeek"print("Name:",string,"age:",int1,"fraction:", float1,end="\n") 

a = b = c =1   #Create an integer object with a value of 1, assign values from back to front, and three variables are assigned the same value
print(a,b,c,end="\n") 

a,b,c =1,2,"WeiyiGeek"  #Two integer objects 1 and 2 are assigned to variables a and b, string objects"runoob"Assigned to variable c.
print(a,b,c,end=" ")

del a,b
print(a,b,c,end=" ")  #Here will say a,b not define (undefined)

Python variable assignment

**Python reserved characters and function help: **
These reserved words cannot be used as constants or variables, or any other identifier names; built-in function help and Python3 output format:

>>> import keyword
>>> keyword.kwlist
[' False','None','True','and','as','assert','async','await','break','class','continue','def','del','elif','else','except','finally','for','from','global','if','import','in','is','lambda','nonlocal','not','or','pass','raise','return','try','while','with','yield']
# BIF=built-in functions  
>>> dir(__builtins__)>>>help(int)>>>print("string")

**Comment in Python: **
Use #''' """ to comment the code. Note that except for the first one, which is used in pairs, comment output can also be performed in the output function;

# We can output the comment of the function in the following example:
def a():'''This is the docstring'''
 pass
print(a.__doc__)  #The output is: This is the docstring

**Python lines and indentation: **
In Python code blocks, {} is no longer used to control classes, functions and other logical judgments like other languages, but in an indented manner;
Therefore, the same number of indented spaces at the beginning of the line must be used in Python code blocks; it is recommended that you use single tab or two spaces or four spaces at each indentation level, remember not Mixed use;

**Meaning of blank lines in Python: **
Use blank lines to separate functions or methods of a class to indicate the beginning of a new piece of code. The class and function entry are also separated by a blank line to highlight the beginning of the function entry.
Blank lines are different from code indentation, which is not part of Python syntax. Do not insert blank lines when writing, and the Python interpreter will run without error; but the function of blank lines is to separate two sections of code with different functions or meanings, which is convenient for future code maintenance or reconstruction; Remember: blank lines are also program codes Part.

**Python multi-line statement: **
Usually a statement is written in one line, but if the statement is very long, we can use backslash () to implement a multi-line statement; but in the multi-line statement in [], {}, or () directly use',' to Split, do not need to use backslash ();
Use multiple statements in the same line, and use a semicolon (;) to separate the statements.

Case: To verify the multi-line statement, split the input statement on one line

#! /usr/bin/python3
# - *- coding:UTF-8-*-
# Function: Verify Python multi-line statements
one =1
two =2
three =3
add = one +\
 two +\
 three
print("add =",add);print(add);   #Use the output on one line;segmentation

Python module import:
Use import or from...import to import the corresponding module in python.

4.3 Python basic data types####

There are six standard data types in Python3:
Number (number) String (string) List (list) Tuple (tuple) Set (collection) Dictionary (dictionary)

4.3.1 Integer (intger)

Python integer data variable

A complex number consists of a real part and an imaginary part, which can be represented by a + bj, or complex (a, b). The real part a and imaginary part b of the complex number are both floating-point types;
E notation: 15e10 => 15*10 to the power of 10 = 150000000000.0; In the interactive mode, the last output expression result is assigned to the variable _.

Case:

>>> price =113.0625>>> _ =0>>> price + _    #Here,_Variables should be treated as read-only variables by users.
113.0625>>> round(_,2)113.06

#! /usr/bin/python3
# - *- coding:UTF-8-*-
# Function: Basic data type,Use with input and output functions

#- - - - integer----#
temp =input("Please enter the number:")print("Input value: ",temp," |Types of:",type(temp))
temp ='5'
number =int(temp)   #Convert characters to integer type
print("Character conversion integer: ",number," |Types of:",type(number))
temp  = True
temp =4+3j  #Plural type
print("plural:",temp," |Types of:",type(temp),end="\n\n")

Python integer data variable case

  1. There is no Boolean type in Python2. It uses the number 0 to represent False and 1 to represent True.
  2. In Python3, True and False are defined as keywords, and their values are still 1 and 0, and they can be added to numbers.
  3. In Python3, hexadecimal and octal are used to represent integers: number = 0xA0F # hexadecimal 0o37 # octal
  4. J can be case-insensitive in negative numbers
4.3.2 String (string)

Single quotes and double quotes in python are exactly the same and the string cannot be changed. Use triple quotes ("' or """) to specify a multi-line string for inter-line, WYSIWYG (what you see is what you get) format;

Python does not support single-character types, and single-characters are also used as a string in Python, such as str ='a'; the string can contain newline characters, tabs, and other special characters.

Python strings can be concatenated with the + operator, repeated with the * operator, and concatenated strings literally. For example, "this" "is" "string" will be automatically converted to this is string.

Python intercepts characters in a string by indexing. The syntax format is as follows: variable [head subscript: tail subscript] (there are two indexing methods, starting with 0 from left to right, and starting with -1 from right to left)
[:] To intercept a part of the string, follow the principle of left closed and right open, str[0,2] does not contain the third character.

Python string index

**Python escape character: **
Backslashes can be used to escape. Use r to prevent backslashes from being escaped. For example, r"this is a line with \n" will display \n instead of a newline.

Python string formatting

**Python string formatting: **
The basic usage is to insert a value into a string with string format character %s, which has the same syntax as the sprintf function in C.

Python string formatting

Python format operator auxiliary instructions

Case:

#! /usr/bin/python3
# coding:utf-8
# Function: Detailed explanation of string type
##- - - - String-----#
word ='String'
sentence ="This is a sentence."
paragraph ="""
 This is a paragraph,
 Can be composed of multiple lines
"""
A =" THIS A"
B ="String !"
C = A + B   #Concatenated string
print(C,end="\n")print("paragraph:",paragraph)

# The grammatical format of string interception is as follows: variable[Head subscript:Tail subscript:Stride] 
str1 ='0123456789'print(str1[0:-1])           #Output all characters from the first to the penultimate
print(str1[2:5])            #Output characters starting from the third to the fifth
print(str1[-2])             #The second number
print(str1 *2)             #Output string twice(Keyword*repeat)print('Value:'+ str1)       #Connection string(Keyword+Splicing)

##- - - - Character escape-----#
print('hello\nWeiyi')     #Use backslash(\)+n escape special characters
print(r'c:\\windows')     #Add an r in front of the string to indicate the original string and will not be escaped

var="Hello"print("Concatenating strings:\a",var[:5]+" World!")

# The original string has almost the same syntax as a normal string except that the letter r is added before the first quotation mark of the string (upper and lower case)
print(r'\n')print(R'\n')print("My name is%s this year%d years old%#X value:%5.3f"%('Xiao Ming',10,255,12.85455)) #Format string
print("\u6211\u662f\u6700\u559c\u7231\u0050\u0079\u0074\u0068\u006f\u006e") #unicode output

# Base conversion
" %o"%10   #'12'||"%#o"%10  #'0o12'"%X"%10    #'A'||"%#X"%10  #'0XA'"%x"%10    #'a'||"%#x"%10   #'0xa'

# Floating point format
" %5.2f"%27.658  #'27.66'"%5.2f"%27         #'27.00'"%f"%27              #float type,Keep 6 digits after the decimal point'27.000000'"%e"%10000000   #'1.000000e+07'"%.2e"%27.658     #'2.77e+01"%g"%28.444455     #Smart choice'28.4445'"%g"%28261465     #'2.82615e+07'"%5d"%5       #'    5'"%-5d"%5      #'5    '-Used for left alignment
" %+d"%5      #'+5'+Used to take positive and negative numbers
" %+d"%-5    #'-5'"%010d"%5   #'0000000005'"%-010d"%5   #Add a negative sign to a left pair,At this time, 0 will not be filled'5print('%s'%"I love you")           #Format string'I love you'(Conventional way)

# %f format fixed-point number,M.N(M is the minimum length,N represents the number of digits after the decimal point?)Recommended method

'{0:1 f}{1}'.format(27.586,"Gb")    # '27.586000Gb''{0:.1f}{1}'.format(27.586,"Gb")   # '27.6Gb'Keep one digit after the decimal point
" %c %c %c"%(97,98,99)         #Format character Ascll code conversion'a b c''%d + %d = %d'%(4,5,4+5)   #Format integer'4 + 5 = 9'>>>"{:+.2f} {:+.2f}".format(3.1415926,-1)  #Signed to keep two decimal places
'+3.14 - 1.00'>>>"{:.0 f}".format(3.1415926,-1)  #Without decimal extraction
'3'>>>"{:0>2 d}".format(3)  #Supplement the left with zero supplement
'03'>>>"{:0<2 d}".format(3)  #Supplement the right side with zero supplement
'30'>>>"{:,}". format(30000000)  #Comma separated number format
'30,000,000'>>>"{:.2 %}".format(0.2657)  #Percentage format
'26.57 %'>>>"{:.2e}".format(10000000000000)  #Index Record
'1.00 e+13'>>>"{:10d}".format(100)  #10 units of width right aligned
'  100'>>>"{:<10 d}".format(100) #Align left
'100  '>>>"{:^10 d}".format(100) #Center aligned
'   100

Python string example

4.3.3 List (list)

Sequence to list is the most basic data structure in Python, and is the most frequently used data type. The operations that can be performed include indexing (starting from 0), slicing (slice combination [start:stop,step]), addition, multiplication, and inspection Members; the types of elements in the list can be different (the key is that it can also be a list); the data items of the Python list can be modified or updated;

Format: The list is a list of elements written between square brackets [] and separated by commas, such as variables [head subscript: tail subscript]. The list can also be indexed and intercepted like a string. After the list is intercepted Return a new list containing the required elements.

Python list

Focus: List comprehension (analysis)
List comprehensions, also called list comprehensions, are inspired by the functional programming language Haskell. It is a very useful and flexible tool that can be used to dynamically create lists.

grammar:

[ For A in B]
Such as: list1=list(x**2for x inrange(10))  #[0,1,4,9,16,25,36,49,64,81])

Case 1:

#! /usr/bin/python3
# coding:utf-8
# Features:Verification list(LIST)
             #-4,-3,-2,-1,0
createlist =[1,1.0,True,"WEIYIGEEK",'c']
pjlist =['Python','Version 3']print(createlist) #Full list

print(createlist[0])   #The first element of the output list
print(createlist[1:3])  #Output from the second to the third element
print(createlist[-3:]) #From the 3rd to the last element(It is particularly worth paying attention to the output of all elements from the third to last element)print(pjlist *2)            #Output list twice
print(createlist + pjlist)   #List splicing

createlist[0]='This is a demo'  #Unlike Python strings, the elements in the list can be changed
print(createlist[:]) #Full list

letters =['h','e','l','l','o']print(letters[1:4:2])  #Step experiment 1-e  3-l

Python list case 1

Case 2:

#! /usr/bin/python3
# coding:utf-8
# Function: Detailed list type
# update list
L=['Google','Runoob','Taobao']print("L[1]Before list modification:",L[1],end=" ")
L[1]='Weiyigeek'print("After modification:",L[1],end="\n")

# Delete list element
del L[2]print("Delete L[2]After the list: ", L)

# List length
print(len(L))

# List combination
print(L+[1,2,3])

# Duplicate list
print(L *2)

# Determine if it is in the list
print('Weiyigeek'in L)

# Iteration
for x inrange(len(L)):print(x,L[x],len(L[x]))

# Nested lists are similar to two-dimensional arrays
x =[[1,2,3],['a','b','c']]print(x[0][1])  #Output 2print(x[1][1])  #Output b#!/usr/bin/python3
# coding:utf-8
# Function: Detailed list type

# V1.Create normal list
L=['Google','Runoob','Taobao']

# V2.Create a mixed list(Nested list)
mix =[1,'list0',2.3,[1,2,3]]

# V3.Create empty list
empty =[]

# Update the list (you can also swap the array)
print("L[1]Before list modification:",L[1],end=" ")
L[1]='Weiyigeek'print("After modification:",L[1],end="\n")

# Delete list element
del L[2]print("Delete L[2]After the list: ", L)

# List length
print(len(L))

# List combination
print(L+[1,2,3])

# Duplicate list
print(L *2)

# Determine if it is in the list
print('Weiyigeek'in L)

# Iteration
for x inrange(len(L)):print(x,L[x],len(L[x]))

# Nested lists are similar to two-dimensional arrays
print(mix[3][1])  #Output 2

# Supplementary list comprehension
list1 =[(x,y)for x inrange(10)for y inrange(10)if x %2==0if y %2!=0] #x is divisible by 2, and y cannot be divisible by 2 for display (x.y)
print(list1)
#[(0,1),(0,3),(0,5),(0,7),(0,9),(2,1),(2,3),(2,5),(2,7),(2,9),(4,1),(4,3),(4,5),(4,7),(4,9),(6,1),(6,3),(6,5),(6,7),(6,9),(8,1),(8,3),(8,5),(8,7),(8,9)]
# Is equivalent to the following
list2 =[]for x inrange(10):for y inrange(10):if(x %2==0)&(y %2!=0):
   list2.append((x,y))print(list2)

# Advanced list comprehensions
list1 =['1.Jost do it','2.Everything is possible','3.Let programming change the world']
list2 =['2.Li Ning','3.Fish C Studio','1.Nick']
list3 =[name+':'+title[2:]for title in list1 for name in list2 if name[0]== title[0]]  #Use list analysis to output when the first character variant of the for loop is consistent
print(list3)  #['1.Nick:Jost do it','2.Li Ning:Everything is possible','3.Fish C Studio:Let programming change the world']

Python list case 2

  1. The value of the elements in the list can be modified, such as list[0] ='This is a demo';
  2. Python list interception can receive the third parameter. The parameter is used to intercept the step size. The following examples are set at index 1 to index 4 and set the step size to 2 (one position apart) to intercept the string;
  3. The list obtained by assignment will change with the order of the parent list,
4.3.4 Tuple

A tuple tuple is a list shackled (the element cannot be changed at will like the numeric/string type). Due to the powerful function of the list, certain restrictions are required.

Format: Tuples are written in parentheses (), and the elements are separated by commas (you can also directly tuple = 1,2,3,4).

We mainly learn from creating and accessing tuples, updating and deleting a tuple, and tuple-related operators:
Concatenation operator (the data types on both sides must be the same)
Repeat operator (8 * (8,))
Relational operators (greater than, less than, etc.)
Member operator ([in] [not in])
Logical operator (not>and>or)

Case:

#! /usr/bin/python3
# coding:utf-8
# Features:Validate Tuple tuple,A list of tuples on the chain
tuple1 =('abc',789,2.23,'WEIYIGEEK',70.2)
pjtuple =('Python','Version 3.7.2')print(tuple1[1:3])       #Print out elements from subscript index 1 to subscript index 2(Note the number of elements 3-1=2)print(pjtuple *2)       #repeat
print(tuple1 + pjtuple)  #Splicing

# Constructing a tuple containing 0 or 1 element is special
tup1 =()    #Empty tuple
tup2 =(20,) #An element, you need to add a comma after the element
print("Empty tuple",tup1)print("An element",tup2)

# Function: a list of tuples on the chain
tup =(1,2,3,4)  #Define a tuple
temp =1,2,3,4   #Another method can also define a tuple(worth learning)print("Types of:",type(temp))  #Types of: <class'tuple'>print("Tuple creation:",8*(8,)) #(There must be a comma in both ways)Tuple creation:(8,8,8,8,8,8,8,8)print("slice:",temp[1:3])  #Slice(You can also use this to copy tuples)slice:(2,3)

temp =('Xiao Ming','Xiaojing','Xiao Chen','Xiao Zheng')
temp = temp[:2]+('Teacher Zheng',)+temp[2:] #Use the slicing method to divide into two segments to add new elements and then join,Pay attention to commas and types. #Concatenated tuples:('Xiao Ming','Xiaojing','Teacher Zheng','Xiao Chen','Xiao Zheng')print("Concatenated tuples:",temp)
del temp #Object-oriented programming languages have recycling mechanisms
print(tup *2)   #(1,2,3,4,1,2,3,4)
L =('Google','Taobao','Runoob')print("{0} , {1} , {2}".format(L[-1],L[1],L[0]))  #Format the output tuple Runoob, Taobao , Google

# Supplement: generator deduction(genexpr)
e =(i for i inrange(10))next(e)  # 1next(e)  # 2next(e)  # 3next(e)  # 4next(e)  # 5for each in e:print(each, end =" ")

# Supplement: Implementation 1+2+3.。。 +100=5050 
Sum =sum( i for i inrange(101))print("Sum =",Sum)  #5050
##### Results of the#####
# 56789
# Sum =5050

Python tuple case

  1. Although the elements of a tuple cannot be changed, it can contain mutable objects, such as lists.
  2. Note the special grammatical rules for constructing tuples containing 0 or 1 elements, and empty tuples.
  3. Tuples/lists/strings all belong to the sequence (sequence) and all have something in common: get elements by index (negative index is supported), and a collection of elements within a range can be obtained by sharding, and there are many common operators Such as repeat operator, splicing operator, membership operator
  4. Tuples do not exist in the list comprehension, but in the generator deduction genexpr;
4.3.5 Set

A set is an unordered sequence of non-repeating elements. It is composed of one or several wholes of different sizes. The things or objects that make up the set are called elements or members. The basic function is to conduct membership tests and Remove duplicate elements.

Format: Use braces {} or set() to create a set; for example, parame = {value01,value02,…}, set(value);

Format: set1={1,2,3,4,5,6}
  set2 =set(1,2,3,4,5,6)

Case:

#! /usr/bin/python3
# coding:utf-8
# Features:Validation set collection(Case sensitive)

student ={"weiyigeek","WEIYIGEEK","Tao Haipeng","Zheng Laogou","Chen Huiming",'WEIYIGEEK'}print(student) #Output collection(Random order), The repeated elements are automatically removed

# Membership test
if'weiyigeek'in student:print("weiyigeek exists!")else:print("does not exist!")

# set can perform set operations
a =set('abracadabra')
b =set('alacazam')

# The following operations are worth learning sets that can be subtracted
print(a - b)     #the difference of a and b
print(a | b)     #Union of a and b
print(a & b)     #the intersection of a and b
print(a ^ b)     #elements in a and b that do not exist at the same time

# Function: set
set1 ={'weiyi','geek',12.345}
set2 =set("Python")print(type(set1),set1)  #Output disorder
print(type(set2),set2)  #Output disorder

print(set1 - set2)   #Similar to list comprehensions, the same collection supports collection comprehensions(Set comprehension)  #{'geek','weiyi',12.345}
a ={x for x in'abcasdsadsa'if x not in'abc'}  #display{'d','s'}character,print(a)Collection supports collection comprehension(Set comprehension)

tuple1 =(1.1,2.2,3.3,ord('a'))  #Must be the same type
print(sum(tuple1))               # 6.6print(sorted([23,56,2,16,96,12,14]))

temp =[23,56,2,16,96,12,14]print(list(reversed(temp)))print(list(enumerate([23,56,2,16,96,12,14])))print((1,2.3,4))

Python collection case

  1. Similar to the list comprehension, the same set supports the set comprehension (Set comprehension)
  2. To create an empty set, you must use set() instead of {}, because {} is used to create an empty dictionary.
4.3.6 Dictionary data (dict)

The dictionary is another variable container model, and can store any type of object, is the cousin of the collection; The difference between the dictionary and the collection is: the elements in the dictionary are accessed through keys, not through Offset access.

A dictionary is a mapping type. An empty dictionary is identified by {}. It is an unordered key (key-must be unique and cannot be repeated): value (value-use immutable type).
Use the constructor dict() to construct a dictionary directly from the sequence of key-value pairs, the format is as follows:

dict(([key,value],[key,value])) #Create a dictionary
dict1 ={'name':"weiyigeek",[key,value]}

Case:

#! /usr/bin/python3
# coding:utf-8
# Features:Dictionary dictionary type is a Key and Value,Used with set collection{}To identify
d ={key1 : value1, key2 : value2 }
d['key1']/**Dictionary access method*/
d['key1]= value   /**Dictionary assignment*/
del d['key1']/**Delete the key value of the specified dictionary*/
del d                   /**Delete dictionary**/

createdict ={}
createdict['one']="1 - Python3"
createdict['two']="2 - Version 3.7.2"
tinydict ={'name':"weiyigeek",'age':21,'love':"Python3 PHP html5 JAVASCRIPT"}print(createdict)  #Output dictionary value/value
print(createdict['one']) #The output key is'one'Value of
print(tinydict.keys()) #Output all keys
print(tinydict.values(),end="\n\n") #Output all values

# Constructor dict()You can build a dictionary directly from a sequence of key-value pairs
cdict1 =dict([('Runoob',1),('Google',2),('Taobao',3)])  #Method 1 Iterable object method to construct a dictionary
cdict2  =dict(Runoob=1, Google=2, Taobao=3)                  #Method 2 Incoming keywords
cdict3  =dict((['a',2],['b',3]))                           #Method 3 Pass in the embedded list
cdict4  =dict(zip(['one','two','three'],[1,2,3]))     #Method 4 mapping function method to construct a dictionary
jiecheng ={x: x**2for x in(2,4,6)}              ##Method 5 Dictionary comprehension
print(cdict1)print(cdict2)print(jiecheng)

# Derivation from dictionary
>>> x ={i: i %2for i inrange(10)}   #Here is the calculation expression
{0:0,1:1,2:0,3:1,4:0,5:1,6:0,7:1,8:0,9:1}>>> y ={i: i %2==0for i inrange(10)}   #Here is the conditional expression
{0: True,1: False,2: True,3: False,4: True,5: False,6: True,7: False,8: True,9: False}

Python dictionary case

  1. A list is an ordered collection of objects, and a dictionary is an unordered collection of objects (similar to JSON)
  2. The key must be unique, but the value is not necessary. The value can take any data type, but the key must be immutable (string, number or tuple)
  3. The same key is not allowed to appear twice. If the same key is assigned twice during creation, the latter value will overwrite the previous value.
  4. Dictionary also has its own derivation

Recommended Posts

Python3 entry learning one.md
Python entry learning materials
Python3 entry learning four.md
Python3 entry learning three.md
Python3 entry learning two.md
Python entry-3
03. Operators in Python entry
Python function basic learning
python_ crawler basic learning
Python entry tutorial notes (3) array
Python regular expression quick learning
Getting started python learning steps
Python magic function eval () learning
05. Python entry value loop statement
Python regular expression learning small example
Python entry notes [basic grammar (below)]
Learning path of python crawler development
Python learning os module and usage
Two days of learning the basics of Python