Tuple & Dictionary & set

Posted by RTT on Sat, 15 Jan 2022 20:11:34 +0100

1, Tuple tuple

1. General

Similar to a list, it is essentially an ordered set

Differences between tuples and lists:

a. list: [] tuple: ()

b. the elements in the list can be added or deleted, but the elements in the tuple cannot be modified [element: once initialized, it cannot be changed]

2. Create tuples

 

Create list:

Create empty list: list1 = []

Create a list with elements: list1 = [element 1, element 2,....]

Create tuple

Create empty tuple: tuple1 = ()

Create tuples with elements: tuple1 = (element 1, element 2,...)

Code demonstration:

# 1. Create an empty tuple
tuple1 = ()
print(type(tuple1))  # <class 'tuple'>
# 2. Create tuples with elements
tuple2 = (12,34,6,87)
print(tuple2)
print(type(tuple2))  # <class 'tuple'>

# 3. Elements in tuples can be of various types
tuple3 = (12,34,4.12,"lala",True,False)
print(tuple3)

# Note: when the tuple created has only one element, a comma will be added after the element,
tuple4 = (2)
print(tuple4)
print(type(tuple4))  # <class 'int'> 

tuple5 = (3,)
print(tuple5)
print(type(tuple5))  #<class 'tuple'>

3. Access to tuple elements

Code demonstration:

tuple1 = (14,32,35,7,87)
# 1. The element of tuple is accessed by subscript. The subscript starts from 0 by default
print(tuple1[1])
# print(tuple1[5])  #  tuple index out of range

print(tuple1[-1])  # 87 the index of the last element of the tuple is - 1
print(tuple1[-3])  # 35

# 2. The element value of tuple cannot be modified
# tuple1[2] = 99
# print(tuple1)  # 'tuple' object does not support item assignment

# 3. Delete tuple del
# del tuple1
print(tuple1)  # name 'tuple1' is not defined

4. Tuple operation

Code demonstration:

# 1. Merge tuples+
tuple1 = (12,34,56)
tuple2 = (3.12,56,"hello")
print(tuple1 + tuple2)

# 2. Repeat elements in tuples*
tuple3 = (23,45,67)
print(tuple3 * 4)

# 3. Judge whether the specified element uses the member operators in and not in in tuples
print(56 in tuple2)
if "hello" in tuple2:
    print("Finally found you")
else:
    print("Where are you?!")

# 4. Truncation (slicing) of tuples
tuple4 = (12,3,5,7,98)
print(tuple4[1:4])   # (3, 5, 7)
print(tuple4[-1:])  # (98,)
print(tuple4[:2])   # (12, 3)

5. Tuple function

Code demonstration:

# Common functions of tuples
#1.len get the length of tuple
print(len(tuple4))  # 5

# 2. Get the maximum value max() and the minimum value min() in the tuple
print(max(tuple4))  # 98
print(min(tuple4))  # 3

# 3. Convert other data types to tuple()
list1 = [12,34,57,89]
print(type(list1))  # <class 'list'>
print(type(tuple(list1))) # <class 'tuple'>

# 4. Traversal tuple
# The first method: for in
for i in tuple4:
    print(i)

# The second way: access by subscript
for i in range(len(tuple4)):
    print(tuple4[i])

# The third way: enumrate() returns the index and element
for key,value in enumerate(tuple4):
    print(key,value)

6. Two dimensional tuple

Code demonstration:

# Two dimensional tuple
tuple2 = (12,34,5,6,(763,341,23),980,89)
print(tuple2)
print(tuple2[3])  # 6
print(tuple2[4][1])  # Access to two-dimensional tuples

2, Dictionary dict

1. Concept

Disadvantages of using lists and tuples: when the stored data needs to be dynamically added and deleted, we generally use lists, but lists sometimes encounter some problems

Solution: it can not only store multiple data, but also easily locate the required elements when accessing the elements, using a dictionary

Syntax: {key 1: value 1, key 2: value 2, key 3: value 3,..., key n: value n}

Description: key value pair: key value

  • Dictionaries, like lists, can be used to store multiple data

  • When finding an element in the list, it is based on the subscript; When finding an element in the dictionary, it is based on the 'name' (that is, the colon: the previous value, such as' name ',' id 'and' sex 'in the above code)

  • Each element in the dictionary consists of two parts, key: value. For example, 'name': 'monitor', 'name' is the key and 'monitor' is the value

  • Keys can use immutable data types such as numbers, Booleans, tuples, and strings, but strings are generally used. Remember not to use variable data types such as lists

  • The key in each dictionary is unique. If multiple identical keys appear, the following value will overwrite the previous value

Usage scenarios:

  • The list is more suitable for saving similar data, such as multiple products, multiple names and multiple times

  • Dictionaries are more suitable for storing different data, such as different information of a commodity and a person

2. Definition dictionary

# 1. Define an empty dictionary {}
dict1 = {}
print(type(dict1))  # <class 'dict'>

#2. Define a non empty dictionary
# The first way to define a dictionary
dict2 = {"name":"urinate","age":25,"love":"female","sex":"**"}  # Most commonly used
print(dict2)
print(type(dict2))
print(dict2["name"],dict2["love"])  # ACCESS Dictionary

# The second way to define a dictionary is dict (key = value, key1 = value1,...) Key means key and value means value
dict3 = dict(num1 = "123",num2 = "987")
print(dict3)

# The third way to define a dictionary
# dict(zip([key1,key2,key3....],[value1,value2,value3......]))
# Note: when the quantity of key and value is inconsistent, the smaller quantity shall be taken as the benchmark
dict4 = dict(zip(['n1','n2','n3'],[12,34,56]))
dict5 = dict(zip(['n1','n2','n3'],[12,34,56,45,67,89]))
print(dict4)
print(dict5)

# The fourth way:
dict6 = dict([("a",10),("b","98"),("c",67),("d",34)])
print(dict6)   # {'a': 10, 'b': '98', 'c': 67, 'd': 34}

3. Dictionary operation

# 1. Access the elements in the dictionary
# The first method: access directly through subscript
dict1 = {"name":"Chinese doctor","author":"Liu Weiqiang","person":"Zhang Hanyu"}
print(dict1['author'])
# print(dict1['money'])  # When accessing a key that does not exist in the dictionary, an error is reported directly

# The second method is to obtain the information through the get() method
print(dict1.get('name'))
print(dict1.get('money'))  # None returns none when accessing a key that does not exist in the dictionary
print(dict1.get('money',10000000))  # When accessing a key that does not exist in the dictionary, if the second parameter is passed, the second parameter will be set to the default value,

#2. Get the dictionary length len()
print(len(dict1))

# 3. Get all the key s in the dictionary
print(dict1.keys())  # dict_keys(['name', 'author', 'person'])

# 4. Get all value s in the dictionary
print(dict1.values()) # dict_values(['Chinese doctor', 'Liu Weiqiang', 'Zhang Hanyu'])

# 5. Get all the key and value items () in the dictionary
print(dict1.items()) # dict_items([('name ',' Chinese doctor '), ('author', 'Liu Weiqiang'), ('person ',' Zhang Hanyu '))

# 6. Traverse the dictionary
'''
#  The first method: for in
for i in dict1:  # Traverse all key s in the dictionary
    print(i)


# The second way: enumrate() traverses all key s in the dictionary
for k,v in enumerate(dict1):
    print(k,'----',v)
   
# The third way: items traverses all key s and value s in the dictionary
for k,v in dict1.items():
    print(k,'----',v)


# The fourth way: traverse all the values in the dictionary
for v in dict1.values():
    print(v)


# Merge dictionary update()
dict2 = {"name":"Yuan Jianxin","money":"1999999","age":23}
dict3 = {"sex":"Fierce man"}
dict2.update(dict3)
print(dict2)
'''

dict4 = {"name":"iPhone13","money":20000,"color":"luxury gold color"}
# increase
dict4["size"] = 6.5
print(dict4)

# change
dict4['color'] = "Sao powder"
print(dict4)

# Delete
# The first: pop() deletes the specified element
#dict4.pop("color")
print(dict4)
# The second method: popitem() randomly returns and deletes the last pair of key and value in the dictionary
dict4.popitem()
print(dict4)

# clear() clear dictionary
dict4.clear()
print(dict4)

3, Assignment, deep copy, shallow copy

#Visual view of deep and shallow copies
http://pythontutor.com/live.html#mode=edit

# Assignment: in fact, it is the reference (alias) of the object
list = [12,34,57,9]
list1 = list
list[1] = 78
# print(list,list1)

# Shallow copy: copies the parent object, not the child object inside the object When copying a one - dimensional list, the two lists are independent
import copy
a = [12,35,98,23]  # One dimensional list
b = a.copy()
a[1] = 67
# print(a,b)

# When copying a two-dimensional list, shallow copy can only copy the outermost list, not the child objects in the parent object. When modifying the values in the child objects, the newly copied objects will also change
c = [14,53,25,[31,89,26],42] # 2D list
d = c.copy()
c[3][1] = 11
print(c,d)

# To solve the problem of shallow copy processing two-dimensional list, you need to use deep copy
e = [14,53,25,[31,89,26],42] # 2D list
f = copy.deepcopy(e)
e[3][1] = 11
print(e,f)

4, set [understand]

1. General

It's basically the same as a mathematical set,

Features: duplicate elements are not allowed. Intersection, union and difference sets can be operated

Essence: a collection of disordered, non repeating elements

2. Create

Set (list or tuple or dictionary)

Code demonstration:

# Create an empty collection
set1 = set()
print(set1)
print(type(set1))  #<class 'set'>

# Create a collection containing elements
set2 = {12,345,633,21}
set3 = {"hello","world","everyone"}
print(set2,set3)
print(type(set2))  # <class 'set'>

3. Operation

# Gets the length of the collection (len)
print(len(set2))  # 4

# Collection cannot access elements through subscripts
# print(set2[3])

3.1 add

Code demonstration:

set2 = {12,345,633,21}
# Add an element add() to the collection
set2.add(98)
print(set2)

# Add multiple elements to the collection through update(). The additional elements appear in the form of a list
set2.update([1,2,3])
print(set2)

3.2 deletion

Code demonstration:

set2 = {12,345,633,21}
# pop() randomly deletes a
set2.pop()
print(set2)

# remove() deletes the specified element. The parameter passed in is the element to be deleted. If the deleted element does not exist, an error will be reported
# set2.remove(22)
set2.remove(2)
print(set2)

# discard() deletes the specified element. The parameter passed in is the element to be deleted. If the deleted element does not exist, no error will be reported
set2.discard(21)
# set2.discard(22)
print(set2)

# clear() clear the collection
set2.clear()
#print(set2)

3.3 traversal

Code demonstration:

set2 = {12,345,633,21}
for i in set2:
    print(i)

3.4 intersection and union

Code demonstration:

# Relationship between sets
set5 = {12,34,56,23,86}
set4 = {23,45,25,12,41}
print(set5 & set4)  # intersection
print(set5 - set4)  # Difference set
print(set5 | set4)  # Union
print(set4 > set5)  # Does set4 contain set5
print(set4 < set5)  # Whether set5 contains set4