First, traverse
Through for ... In ... Syntax structure, we can traverse string, list, tuple, dictionary and other data structures.
1. String traversal
A_str = "Hello World"
For Char in A_STR:
Print (char,end= ")
2. List traversal
A_list = [1,2,3,4,5]
For num in a_list:
Print (num,end= ")
3, meta-group traversal
A_tuple = (1,2,3,4,5)
For num in a_tuple:
Print (num,end= ")
4. Dictionary traversal
1) Traversing the key of the dictionary
Dict = {' name ': ' Zhanshi ', ' sex ': ' m '}
For key in Dict.keys ():
Print (key)
2) Iterate through the value of the dictionary
Dict = {' name ': ' Zhanshi ', ' sex ': ' m '}
For value in Dict.values ():
Print (value)
3) Iterate through the elements of the dictionary
Dict = {' name ': ' Zhanshi ', ' sex ': ' m '}
For item in Dict.items ():
Print (item)
2) traversing the key-value of the dictionary
Dict = {' name ': ' Zhanshi ', ' sex ': ' m '}
For Key,value in Dict.items ():
Print (Key,value)
5, subscript index traversal, enumerate ()
chars = [' A ', ' B ', ' C ', ' d ']
i = 0
For Char in chars:
Print ('%d%s '% (I,char))
i + = 1
Enumerate ()
chars = [' A ', ' B ', ' C ', ' d ']
For I,char in Enumerate (chars):
Print (i, char)
Ii. public methods (for strings, lists, tuples, dictionaries)
1. Operators
- Merge, in addition to dictionaries, the other three types are supported
- Copy, in addition to the dictionary, the other three types are supported
The in element is supported, PS: When operating on a dictionary, the dictionary key is judged.
Does not exist in the element, both support
2. Built-in functions
CMP (ITEM1,ITEM2) compares two values, PS: When comparing dictionaries, compare the keys first, then compare the values.
Len (item) calculates the number of elements in the container, PS: The number of key-value pairs returned when manipulating a dictionary.
Max (item) returns the maximum value of the element in the container
MIN (item) returns the minimum value of the element in the container
Del (item) Delete variable del variable "subscript" del (variable name)
3. References
In Python, values are passed by reference.
mutable types and immutable types
Variable type, the value can be changed, the address is the same: list, dictionary dict
Immutable types, values cannot be changed, address changes: Numeric type (int,long,bool,float), String (str), tuple (tuple).
4, how to exchange the value of 2 variables: 1) a,b=b,a 2) Reference temporary variable 3) a=a+b B =-a a=a-a
Python Small white road (feature syntax three traversal, public method, reference)