Python basic Syntax (ii)
--------------------------------------------the basic syntax of Python (i)--------------------------------------------
2. Tuples
The tuple and list are very similar, but the tuple is immutable, that is, the tuple cannot be modified, the tuple is defined by a comma-separated item in parentheses, and the index and slice operations are supported;
See if an element is in a tuple. An empty tuple (); a tuple containing only one element ("a",) #需要加个逗号
Advantage: A tuple is faster than a list and ' write-protected ' for data that does not need to be modified, which can be more secure code
The tuple and list can be converted to each other, using the built-in functions list () and tuple ().
L = [1, 2, 3]
Print L # [1, 2, 3]
t = tuple (L)
Print t # (1, 2, 3)
L1 = List (t)
Print L1 #[1, 2, 3]
The most common usage of tuples is in the print statement, as in the following example:
Name = "Peter Zhang"
Age = 25
Print "Name:%s; Age:%d '% (name, age)
# Name:peter Zhang; Age:25
The functions are as follows:
count (value) ---Returns the number of elements in a tuple that have values of value
t = (1, 2, 3, 1, 2, 3)
Print T.count (2) # 2
Index (value, [Start, [stop]]) ---Returns the index of the first occurrence in the list that is value, and if not, the exception valueerror
t = (1, 2, 3, 1, 2, 3)
Print T.index (3) # 2
Try
Print T.index (4)
Except ValueError, ve:
Print "There is no 4 in tuple" # There are no 4 in tuple
3. Dictionaries
A dictionary consists of a key-value pair, which must be unique; eg:d = {key1:value1, key2:value2}; Empty dictionaries are denoted by {}; the key-value pairs in the dictionary are not sequential, if you want to
A particular order, then they need to be sorted before use; D[key] = value, if there is already a key in the dictionary, assign it as value, otherwise add a new key-value pair key/value;
Use del D[key] to delete a key-value pair, to determine if there is a key in the dictionary, and to use in or not;
D = {}
d["1"] = "one"
d["2"] = "both"
d["3"] = "three"
Del d["3"]
For key, value in D.items ():
Print "%s to%s"% (key, value)
#1-One
#2--
The Dict function is as follows:
Clear () ---Delete all the elements in the dictionary
D1 = {"1": "One", "2": "One"}
D1.clear ()
Print D1 # {}
Copy () ---Returns a copy of the dictionary (shallow copy)
D1 = {"1": "One", "2": "One"}
D2 = D1.copy ()
Print D2 #{' 1 ': ' One ', ' 2 ': ' One '}
Dict.fromkeys (seq,val=none) ---Create and return a new dictionary with the key to the dictionary in sequence seq, Val is the initial value corresponding to all keys in the dictionary (default is None)
L = [1, 2, 3]
t = (1, 2, 3)
D3 = {}.fromkeys (l)
Print D3 #{1:none, 2:none, 3:none}
D4 = {}.fromkeys (t, "Default")
Print D4 #{1: ' Default ', 2: ' Default ', 3: ' Default '}
get (Key,[default]) ---Returns the dictionary dict key key corresponding value, if this key is not present in the dictionary, returns the value of default (default defaults to None)
d5 = {1: "One", 2: "One", 3: "Three"}
Print D5.get (1) #one
Print D5.get (5) #None
Print D5.get (5, "test") #test
Has_key (KEY) ---Determine if there are key keys in the dictionary
D6 = {1: "One", 2: "One", 3: "Three"}
Print D6.has_key (1) #True
Print D6.has_key (5) #False
items () ---Returns a list that contains a tuple (key, value) in the dictionary
D7 = {1: "One", 2: "One", 3: "Three"}
For item in D7.items ():
Print Item
# (1, ' one ')
# (2, ' both ')
# (3, ' three ')
For key, value in D7.items ():
Print "%s--%s"% (key, value)
#1--One
#2--
#3--Three
keys () ---Returns a list that contains all the keys in the dictionary
D8 = {1: "One", 2: "One", 3: "Three"}
For key in D8.keys ():
Print key
#1
#2
#3
values () ---Returns a list that contains all the values in the dictionary
D8 = {1: "One", 2: "One", 3: "Three"}
For value in D8.values ():
Print value
#one
#two
#three
Pop (key, [default]) ---If the key key exists in the dictionary, deletes and returns Dict[key], if it does not exist and does not give the default value, throws a Keyerror exception
D9 = {1: "One", 2: "One", 3: "Three"}
Print D9.pop (1) #one
Print D9 #{2: ' Both ', 3: ' Three '}
Print D9.pop (5, None) #None
Try
D9.pop (5) # raise Keyerror
Except Keyerror, ke:
Print "keyerror:", Ke #KeyError: 5
popitem () ---Delete any key-value pairs and return the key-value pair, which generates an exception if the dictionary is empty Keyerror
D10 = {1: "One", 2: "One", 3: "Three"}
Print D10.popitem () # (1, ' one ')
Print D10 #{2: ' Both ', 3: ' Three '}
SetDefault (Key,[default]) ---if there is a key in the dictionary, then the Vlaue value is returned, if there is no key, then the key is added, the value is default, none
D = {1: "One", 2: "One", 3: "Three"}
Print D.setdefault (1) #one
Print D.setdefault (5) #None
Print d #{1: ' One ', 2: ' One ', 3: ' Three ', 5:none}
Print D.setdefault (6, "six") #six
Print d #{1: ' One ', 2: ' One ', 3: ' Three ', 5:none, 6: ' Six '}
Update (DICT2) ---Add dict2 elements to the dict, which overrides the key values in the dict when repeated
D = {1: "One", 2: "One", 3: "Three"}
D2 = {1: "First", 4: "Forth"}
D.update (D2)
Print d #{1: ' First ', 2: ' Both ', 3: ' Three ', 4: ' Forth '}
The viewitems () ---Returns a list of a View object, (key, value) pair, similar to a view. The advantage is that if the dictionary changes, the view will change synchronously. In
The dictionary is not allowed to change during the iteration, otherwise it will report an exception
D = {1: "One", 2: "One", 3: "Three"}
For key, value in D.viewitems ():
Print "%s-%s"% (key, value)
#1-one
#2-two
#3-three
viewkeys () ---Returns a list of view objects, key
D = {1: "One", 2: "One", 3: "Three"}
For key in D.viewkeys ():
Print key
#1
#2
#3
viewvalues () ---Returns a list of view objects, value
D = {1: "One", 2: "One", 3: "Three"}
For value in D.viewvalues ():
Print value
#one
#two
#three
4. Sequence
A sequence type is a sequence of elements within a container that is accessed from a 0-based index, one or more elements at a time, and lists, tuples, and strings are sequences; The two main features of a sequence are
Index operators and slicing operators; indexes can get specific elements; slices can get partial sequences;
1 numbers = ["Zero", "one", "one", "three", "four"]
3 Print Numbers[1] # One
4 print Numbers[-1] # Four
5 #print numbers[5] # raise Indexerror
7 print numbers[:] # [' Zero ', ' one ', ' one ', ' three ', ' four ']
8 print Numbers[3:] # [' Three ', ' four ']
9 Print Numbers[:2] # [' Zero ', ' one ']
Print Numbers[2:4] # [' A ', ' three ']
The first number in the slice operator (preceded by a colon) indicates where the slice begins, and the second number (after the colon) indicates where the slice ends. If you do not specify a first number, Python
The beginning of the sequence. If you do not specify a second number, Python stops at the end of the sequence. Note that the returned sequence starts at the start position and ends just before the end position. That is, the starting position is
Contained in a sequence slice, and the end position is excluded from the slice. You can make slices with negative numbers. Negative numbers are used at the beginning of the end of the sequence.
5. Binding
When creating an object and assigning it a variable, the variable simply "points" to that object, not the object itself! In other words, the variable name points to the computer that stores the
The memory of the object, which is known as the name-to-object binding .
If you want to copy a list or a similar sequence or other complex object (not a simple object such as an integer), you must use the slice operator to get the copy.
----------------------------------------------See continued Python basic Syntax (iii)----------------------------------------------
Python basic Syntax (ii)