Introduction notes to Python (issue 5 - Application of sequences 2)

Posted by Noumes on Thu, 10 Feb 2022 02:52:23 +0100

preface:
This article is for python beginners to learn by themselves. In the future, it should be updated every weekend. Because I am also learning python by myself, I want to share a wave of notes. You can pay attention if you like.
Text:
Next, we talked about tuples and dictionaries in this chapter. The three of them (list, tuple and Dictionary) are very similar, which can be compared to memory.
1, Tuple:
It is similar to a list, except that all elements are placed in parentheses, and adjacent elements are separated by ",". The contents of tuples can also be any data type. The main difference between tuples and lists is that tuples are immutable sequences and lists are changeable sequences.

1. Creation and deletion of tuples
Format:

tuplename = (element1,element2,element3)
parametermeaning
tuplenameThe name of the tuple, which conforms to the naming convention
element1There is no limit on the number and type of elements in tuples

It is similar to creating a list, except that [] is replaced by (). In fact, our parentheses can also be omitted. We only need to separate a group of values with commas, which is tuples.
For example:

str1="study hard","make progress every day"
print(str1)      #Output ('Study hard ',' make progress every day ')

However, one thing to note is:
When there is only one element in the tuple, we need to add "," after the element. If "," is not added, the variable type is string type.
Let's introduce a function first, and give the following example
Type() can test the type of variable, and the name of the variable to be tested is put directly in parentheses.

varse1 = ("come on.",)
varse2 = ("come on.")
print("varse1 The types of are:",type(varse1))
print("varse2 The types of are:",type(varse2))

The operation results are as follows:

This is the difference between adding a comma and not adding a comma. There is still a big difference. So, be sure to add commas!!!

2. Create an empty tuple

emptytuple = ()

Create an empty tuple named emptytuple

3. Create a numeric tuple
This is the same as the list, using the tuple () function
Format:

tuple(data)

Data represents data that can be converted into tuples. Its types can be range () objects, strings, tuples (can be nested)

num=tuple(range(10,20,2))
print(num)       #Output (10, 12, 14, 16, 18)

4. Delete tuples
Format:

del name       #Name is the name of the tuple to be deleted

However, python has its own garbage collection mechanism, so we don't need to delete it ourselves.

5. Access tuple element
Direct access with index
Format:

print(untitle[0])

untitle: indicates the name of the access tuple.
The code is as follows:

name = ("Zhang Zifeng","He Jiong","Huang Lei","Wang Yuan","Juen-Kai Wang")
print(name[0])

The operation results are as follows:

Of course, for tuples, you can also obtain the specified elements by slicing
For example:

name = ("Zhang Zifeng","He Jiong","Huang Lei","Wang Yuan","Juen-Kai Wang")
print(name[:3])

The operation results are as follows:

As can be seen from the above two columns, when accessing a single element in a tuple, the output does not include parentheses. If it is a string, the output is not quoted. However, when accessing multiple elements, the output is not only enclosed in parentheses, but also enclosed in single quotes.

6. Modify tuple element
At the beginning of the article, we said that tuples cannot be modified. Now we have to say that tuple elements can be modified, as if I had a serious disease. We can re assign tuples, but we can re assign tuples. It's like modifying tuples. Take a small example.

name = ("Zhang Zifeng","He Jiong","Huang Lei","Wang Yuan","Juen-Kai Wang")
print(name[:3])
name = (95,69,88,49,83,98,45,68,5,6,46)
print(name[:3])

The operation results are as follows:

In addition, we can connect and combine tuples. We use "+" to connect

name = ("Zhang Zifeng","He Jiong","Huang Lei","Wang Yuan","Juen-Kai Wang")
print(name)
name = name+(35,65,65,66,98,76,53)
print(name)

The operation results are as follows:

It should be noted that tuples can only be connected with tuples, and strings, lists, etc. cannot be connected with tuples. In addition, when the connected tuple has only one element, don't forget to add a comma after it.

7. Tuple derivation
The tuple derivation is the same as that of the list, except that [] is changed to (), but there is still a slight difference.
The result generated by tuple derivation is not a tuple, but a generator object, which we need to convert into tuples
Function converted to tuple: tuple()
Function converted to list: list()

number = (i for i in range(3))
print(number)
number = tuple(number)
print(number)

The operation results are as follows:

The first output is the generator object, and the second is the tuple converted by the generator object.
In addition, it can be output through the for loop

number = (i for i in range(3))
for i in number:
    print(i,end=" ")
print(number)
number = tuple(number)
print(number)

The operation results are as follows:

Carefully look at the running results. Only one () is output in the last one, because the original generator object no longer exists after the for loop is traversed. If you want to use the generator object again, you must create a generator object.

2, Dictionary
Dictionaries are similar to lists, but they are disordered and variable sequences. The stored contents are stored in the form of "key value pair", which is equivalent to the relationship between Pinyin and Chinese characters in Xinhua dictionary. Pinyin is equivalent to keys and Chinese characters are equivalent to values.

The dictionary features are as follows:
1. Read by key instead of index
2. A dictionary is an unordered collection of arbitrary objects
3. Dictionaries are variable and can be nested arbitrarily
4. The key in the dictionary must be unique
5. The keys in the dictionary must be immutable and can be tuples.

1. Creation and deletion of dictionary
Formally, a {} is used to enclose the key and value respectively with '', and the key and value are separated with ":".
Format:

dictionary = {'key':'value1','key':'value1'}
parametermeaning
dictionaryDictionary name
keykey
value1value

(1) Create an empty dictionary

dictionary = {}
dictionary = dict()

The method of dict () can not only create an empty dictionary, but also quickly create a dictionary through the existing data
(2) Create dictionary through mapping function
Format:

dictionary = dict(zip(list1,list2))
parametermeaning
dictionaryDictionary name
zip()Combine the corresponding positions of multiple lists or tuples into tuples, and return the zip object of these contents. If you want to get tuples, you can use the tuple () function to convert zip objects into tuples. If you want to get lists, you can use the list () function to convert them into lists
list1The key that specifies the dictionary to be generated
list2Used to specify the value of the dictionary to be generated. If list1 and list2 are different in length, they are the same as the shortest list length

The code is as follows:

name = ["Zhang Zifeng","Wang Yuan","Juen-Kai Wang"]
sign = ["Virgo","scorpio","Virgo"]
dictionary = dict(zip(name,sign))
print(dictionary)

The operation results are as follows:

(3) Create a dictionary with a given key value pair

dictionary = dict(key1=value1,key2=value2,key3=value3)
parametermeaning
dictionaryDictionary name
keyDictionary keys must be unique and immutable. They can be strings, numbers, or tuples
valueDictionary value

For example:

dictionary = dict(Zhang Zifeng="Virgo",Wang Yuan="scorpio",Juen-Kai Wang="Virgo")
print(dictionary)

The operation results are as follows:

Why not use double quotation marks for this key (personal opinion: because the key is immutable. I haven't found a reason to convince me. You can say it in the comment area)
You can also use the fromkeys () method of the dict object to create a dictionary with an empty value.

dictionary = dict.fromkeys(list1)

Parameter Description:

parametermeaning
dictionaryDictionary name
list1Represents a list of dictionary keys

example:

name = ["Zhang Zifeng","Wang Yuan","Juen-Kai Wang"]
dictionary = dict.fromkeys(name)
print(dictionary)

The operation results are as follows:

In addition, if you want to create a dictionary through existing lists and tuples, you can use the following code:

name = ("Zhang Zifeng","Wang Yuan","Juen-Kai Wang")
sign = ["Virgo","scorpio","Virgo"]
dictionary = {name:sign}
print(dictionary)

The operation results are as follows:

be careful:
Dictionary keys can only be tuples. Otherwise, an error will be reported.

(4) Dictionary deletion
Like list tuples, unnecessary dictionaries can be deleted with del

del dictionary

When you only want to delete all the elements in the dictionary, you can use clear (), and the dictionary will become an empty dictionary.

dictionary.clear()

2. Access the dictionary

(1) Access elements by key
Access dictionary is to access the value of element through key, but when the key you want to access does not exist, the system will report an exception. We give a conditional expression to solve it.

dictionary = {"Zhang Zifeng":"Virgo","Wang Yuan":"scorpio","Juen-Kai Wang":"Virgo"}
print(dictionary["Zhang Zifeng"] if 'Zhang Zifeng' in dictionary else "There is no such person in the dictionary")
print(dictionary["He Jiong"] if 'He Jiong' in dictionary else "There is no such person in the dictionary")

The operation results are as follows:

(2) Access the element value through the get() function
Format:

dictionary.get(key,[default])

Parameter Description:

parametermeaning
dictionaryDictionary name
keykey
defaultOptional, used to specify that a default value is returned when the key does not exist, and None if omitted

Example:

dictionary = {"Zhang Zifeng":"Virgo","Wang Yuan":"scorpio","Juen-Kai Wang":"Virgo"}
print(dictionary.get("Zhang Zifeng"))
print(dictionary.get("He Jiong"))
print(dictionary.get("He Jiong","There is no such person in the dictionary"))

The operation results are as follows:

3. Traverse the dictionary
Format:

dictionary = items()

The return value is a list of key value pair tuples that can be traversed. You need to traverse the tuple list through the for loop, as follows:

dictionary = {"Zhang Zifeng":"Virgo","Wang Yuan":"scorpio","Juen-Kai Wang":"Virgo"}
for item in dictionary.items():
    print(item)

The operation results are as follows:

If you want to get each specific key and value, you can set two variables in the for loop

dictionary = {"Zhang Zifeng":"Virgo","Wang Yuan":"scorpio","Juen-Kai Wang":"Virgo"}
for key,value in dictionary.items():
    print(key,"Your constellation is",value)

The operation results are as follows:

4. Add, modify and delete dictionary elements

(1) Add and modify

dictionary[key] = value

Parameter Description:

parametermeaning
dictionaryDictionary name
keyThe key to add an element must be unique and immutable. It can be string, number or tuple
valueThe value of the element to be added can be any data type

If the newly added key duplicates the existing key, the value of the original key will be replaced with the new value, which is equivalent to a modification operation.
The code is as follows:

dictionary = {"Zhang Zifeng":"Virgo","Wang Yuan":"scorpio","Juen-Kai Wang":"Virgo"}
dictionary["He Jiong"] = 'Taurus'
print(dictionary)
dictionary["Zhang Zifeng"] = 'aquarius'
print(dictionary)

The operation results are as follows:

(2) Delete
Delete is the same as deleting the whole dictionary, but when the deleted element does not exist, the system will throw an exception.
Look at the code:

dictionary = {"Zhang Zifeng":"Virgo","Wang Yuan":"scorpio","Juen-Kai Wang":"Virgo"}
if "Wang Yuan" in dictionary:
	del dictionary["Wang Yuan"]
print(dictionary)

The operation results are as follows:

5. Tuple derivation
There is no difference between the list of the first issue of Python and the list of the first issue of Python!
Combined with these two articles, you should know more or less about lists, tuples and dictionaries! That's all for this section. I hope you can sum up the differences and connections between the three. Don't confuse them.

Finally, if you like it, pay attention!