Python dictionary, tuple, list, set collection, sequence

Dictionary

Creation of dictionary

"""
How to create a dictionary
"""
# The first way
dict1 = {"zs": "Zhang San", "ls": "Li Si", "ww": "Wang Wu"}
print(dict1["zs"])
# Dictionary elements can be added dynamically by assigning values to non-existing ones.
dict1["zl"] = "Zhao Liu"
print(dict1)

# The second method is created through dict(), and the parameters are passed in in the form of key = value, where the key cannot be quoted.
dict2 = dict(zs="Zhang San", ls="Li Si", ww="Wang Wu")
print(dict2)

dict3 = dict({("zs", "Zhang San"), ("ls", "李四"), ("ww", "Wang Wu")} )
print(dict3)

dict4 = dict({"zs": "Zhang San", "ls": "Li Si", "ww": "Wang Wu"})
print(dict4)

dict5 = dict({"zs": "Zhang San", "ls": "Li Si"}, ww="Wang Wu")
print(dict5)

dict6 = dict(zip({"zs", "ls", "ww"}, {"Zhang San", "Li Si", "Wang Wu"}))
print(dict6)

Dictionary addition, deletion, modification and query

"""
Dictionary addition, deletion, modification and search
Increase:
    fromkeys(iterable[ ,values])
        Suitable for creating a dictionary from scratch and can quickly initialize a dictionary
Delete:
    pop(key[,default])
        Delete the specified element in the dictionary and return the deleted element
        If the deleted element does not exist, an exception will be thrown, but if the default parameter is passed in, default will be returned.
    popitem()
        Before python3.7, a key-value pair in the dictionary was randomly deleted.
        After 3.7, delete the last key-value pair added in the dictionary.
        Returns the deleted key-value pair
    Both the del operator and clear() function can be used
change :
    You can directly modify a single element through dictionary [key] = value.
    update([other])
        Pass multiple key-value pairs to the function, or pass in another dictionary, or an iterable object containing key-value pairs.
        Modify the values of multiple key-value pairs with one click
check :
    You can search directly through dictionary [key], but if the key is not in the dictionary, an error will be reported.
    get(key[ ,default])
        Pass in the default parameter and return default when the key does not exist
    setdefault(key[,default])
        When key is not found, add dictionary[key] = default to the dictionary and return default
    items()
        Get all key-value pairs of the dictionary
    keys()
        Get all keys of dictionary
    values()
        Get all values of dictionary
"""
# increase
d = dict.fromkeys("python", 1)
print(d) # {'p': 1, 'y': 1, 't': 1, 'h': 1, 'o': 1, 'n\ ': 1}
# Modify the value of a key. If the key does not exist, a new one will be created.
d['p'] = 10
print(d)

# Delete pop()
print(d.pop('y')) # 1
# print(dict.pop('4')) # throw exception
print(d.pop('4', "No such element")) # No such element
#popitem()
print(d.popitem()) # ('n', 1)

# Change update()
d = dict.fromkeys("pyth")
print(d) # {'p': None, 'y': None, 't': None, 'h': None}
d.update({"p": 1, "y": 2})
print(d) # {'p': 1, 'y': 2, 't': None, 'h': None}
d.update(t=3, h=4) # Keys cannot be quoted.
print(d) # {'p': 1, 'y': 2, 't': 3, 'h': 4}

# check
#get()
print(d.get("p")) # 1
print(d.get("a", "Does not exist")) # Does not exist
#setdefault()
print(d.setdefault("p", "11")) # 1
print(d.setdefault("a", "aaa")) # aaa
print(d) # {'p': 1, 'y': 2, 't': 3, 'h': 4, 'a': 'aaa'}

# items() keys() values()
items = d.items()
keys = d.keys()
values = d.values()
print(items)
print(keys)
print(values)

Shallow copy of dictionary

"""
Shallow copy of dictionary
    copy()
"""
d = dict.fromkeys("python", 1)
d1 = d.copy()
print(d1) # {'p': 1, 'y': 2, 't': 3, 'h': 4, 'a': 'aaa'} 

Dictionary nesting

"""
Dictionary nesting
"""
# Nested dictionaries within dictionaries
d = {"zs": {"Chinese": 90, "Mathematics": 87}}
# Access dictionaries within dictionaries
print(d["zs"]["中文"]) # 90
# Nested lists in dictionaries
d = {"zs": [10, 20, 30]}
print(d["zs"][0]) # 10

Dictionary derivation

"""
Dictionary comprehension (same as list comprehension)
    {express for target in iterable}
    {express for target in iterable if condition}
"""
d = {"a": 1, "b": 2, "c": 3}
dd = {v: k for k, v in d.items()}
print(dd) # {1: 'a', 2: 'b', 3: 'c'}

user = {"username": "user_exist", "password": "123456"}
user.update({"confire": "123"})
print(user)

List

Add list

"""
List addition
    append()
    extend()
"""
heroes = [1, 2, "hangsan"]

#Add elements to the end of the list
heroes.append([1,2,3]) #Append a list
print(heros)

#Add multiple elements to the list at once
heroes.extend(["a","b","c"]) # The parameter is an iterable object (list, tuple, string, etc.)
heroes.extend("1ds") # The parameter is an iterable object (list, tuple, string, etc.)
print(heros)

# You can also use slices to implement the append() and extend() methods
s = [1,2,3]
s[len(s):] = [4]
"""
The following writing methods will report errors
s[4:] = 5
s[4] = [5]
s[4] = 5
"""
print(s)

#Insert an element at any position in the list: insert(position to be inserted, element to be inserted)
s = [1,3,4,5]
s.insert(1,2)
print(s)
# Insert an element at the last position of the list, which is equivalent to the append() method
s.insert(len(s),6)
print(s)

Delete list

"""
List deletion
remove()
    (1) When there are multiple identical elements in the list, the command deletes the first matching element.
    (2) If the deleted element does not exist in the list, an error will be reported
pop(): delete the element at the specified position
clear(): clear the list
"""
s = [1, 3, 4, 5]
s.append(2)
s.remove(2)
# s.remove(11) # ValueError: list.remove(x): x not in list
print(s)

# Delete an element at a certain position: pop (subscript of the element to be deleted), return the deleted element
x = s.pop(0)
print(x)
print(s)

# clear the list
s.clear()
print(s)

Modification list

"""
List modifications
"""

s = [1, 2, 3, 4, 5]
# Modify an element at a certain position by index
s[2] = "str"
print(s)

# Use slicing to replace multiple elements at once
# Clear the content at the position specified to the left of =
# Then insert the fragment in the iterable object on the right side of = into the deleted position on the left
# The content on the right can be more, less, or equal to the deleted content on the left
# You can replace all elements after the slice position with elements to the right of =
s[3:] = ["s", "a", "b", "23"]
print(s)

List sorting and flipping

"""
List sorting sort()
List flip reverse()
Both of the above methods will change the original array
"""
nums = [4, 3, 6, 47, 35, 9, 2, 5, 3]
nums.sort() #Default ascending order
print(nums)

# Implement descending sorting: you can reverse the results of ascending sorting
nums.reverse()
print(nums)
# The second method to implement descending sorting, pass in a reverse = True parameter
nums = [4, 3, 6, 47, 35, 9, 2, 5, 3]
nums.sort(reverse=True) # Sort in descending order
print(nums)

List search

"""
List search
count (element to be found): Find the number of times an element appears in the list
index (element to be found): Find the index of the element in the list
    An error will be reported when the element cannot be found
    When the list has multiple identical elements, return the index of the first element found
    You can also specify a range: index (element to be found, start, end)
        Returns the first element in the range start~end, excluding the position of end
"""
nums = [3, 2, 5, 2, 3, 5, 3, 1, 8, 7]
# count (element to be found): Find the number of times an element appears in the list
count = nums.count(3) # Find the number of times element 3 appears in the list
print(count)

# index (element to be found): Find the index of the element in the list
# When the list has multiple identical elements, return the index of the first element found
index = nums.index(5)
print(index)
nums[nums.index(3)] = "change to string 3"
print(nums)
# print(nums.index(78)) # Report error

List copy

"""
copy of list
    (1) Method 1: copy()
    (2) Method 2: Slicing
    (3) Method 3: Import the copy module and call copy() in the module: copy.copy (list to be copied)
    (4) Method 4: Deep copy, call deepcopy() in the copy module: copy.deepcopy (list to be copied)
    The above three types of copies (1) (2) (3) are all shallow copies.
"""
nums = [3, 2, 5, 2, 3, 5, 3, 1, 8, 7]
# copy() method
copy_nums1 = nums.copy()
print(copy_nums1)
# Slicing method
copy_nums2 = nums[:]
print(copy_nums2)

nums = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
copy_nums = nums.copy()
nums[0][0] = 11
# Modify the list element nums[0][0], copy_nums is also affected, so copy() is a shallow copy
print("copy_nums:", copy_nums)
# deep copy
import copy

nums = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
copy_nums = copy.deepcopy(nums)
nums[0][0] = 11
# Modify the list element nums[0][0], copy_nums is also affected, so copy() is a shallow copy
print("copy_nums deep copy:", copy_nums)

List addition and multiplication

"""
List addition and multiplication
    Addition: that is, the splicing of lists, requiring lists on both sides of the plus sign
    Multiplication: Repeat all elements in a list several times
"""
list1 = [1, 2, 3]
list2 = [4, 56]
# list2 = 4 # Report an error, if there are lists on both sides of the plus sign
# Addition of lists
print(list1 + list2)
# Multiplication of lists
print(list1 * 2)

Nested lists

"""
Nested lists
"""
# Two ways to write nested lists
list1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
list2 = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]
print(list1)
print(list2)

# Access to nested lists
for i in list1:
    for j in i:
        print(j, end=" ")
    print()

print(list1[0][0])

#Create a two-dimensional list
a = [0] * 3
# print(a)
for i in range(len(a)):
    a[i] = [0] * 3
print(a)

# [[0,0,0]]
# The following way of creating a two-dimensional list seems correct, but in fact there will be problems
b = [[0] * 3] * 3 # [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
#Existing problems
# Only modify the first element in the first list,
# But actually it is: b = [[1, 0, 0], [1, 0, 0], [1, 0, 0]]
b[0][0] = 1
print(b)
#Cause of the problem:
# Under normal circumstances, different lists point to different addresses, so when one element is modified, it will not affect other elements.
print(a[0] is a[1] is a[2]) # False
# But multiplying elements in the list only references the original content multiple times, and does not actually open up new memory space.
# So something went wrong
print(b[0] is b[1] is b[2]) # True

"""
is and is not are called identity operators and are used to detect whether the id values of objects are equal, that is, to determine whether two variables are the same object.
In python, every object has three attributes, unique identification (id), type and value
id value: It exists when the object is created, cannot be modified, and there will be no duplicate values.

in and not in determine inclusion issues
The in operator is used to determine whether an element is included in the sequence
The not in operator is used to determine whether an element is not included in the sequence
"""
# is operator: Check whether two variables point to the same object
str1 = "zhangsan"
str2 = "zhangsan"
print(str1 is str2) # True
list1 = [1, 2, 3]
list2 = [1, 2, 3]
print(list1 is list2) # False

List comprehension

"""
list comprehension
    Basic syntax: [express for target in iterable]
        The result of a list comprehension must be a list, so square brackets [] are required.
    List comprehensions are more efficient than for loops
"""
# Use list comprehension to multiply each element in the list by 2
list = [1, 2, 3, 4, 5]
list = [i * 2 for i in list]
print(list)

list = [i for i in range(5)]
print(list)

list = [i + 1 for i in range(5)]
print(list)

list = [c * 2 for c in "zhangsan"]
print(list)

# ord() converts a single string to the corresponding encoding
list = [ord(c) for c in "zhangsan"]
print(list)

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]
# Extract the second column element of each row in the two-dimensional list
list = [i[1] for i in matrix]
print(list)
#Extract the subdiagonal elements of the two-dimensional list
list = [matrix[i][2 - i] for i in range(3)]
print(list)

# Create a two-dimensional list using list comprehensions
list = [[0] * 3, [0] * 3, [0] * 3]
print(list)
list[0][0] = 1
print(list)
# Replace the above code with list comprehension
list1 = [[0] * 3 for i in range(3)]
print(list1)
list1[0][0] = 1
print(list1)

"""
Advanced version of list comprehension (add conditional judgment)
    Basic syntax: [express for target in iterable if condition]
    After each iteration of the for statement is executed, the if conditional judgment will be executed first, and finally the expression on the left will be executed.
    That is, the sequence is: for statement iteration --> if conditional judgment --> expression on the left
"""
list = [i for i in range(10) if i % 2 == 0]
print(list) # [0, 2, 4, 6, 8]
list = [i + 1 for i in range(10) if i % 2 == 0]
# becomes an odd number, proving that the last expression on the left is executed
print(list) # [1, 3, 5, 7, 9]

"""
Nested list comprehensions
    Basic syntax: [express for target1 in iterable1
                     for target2 in iterable2
                           .....
                     for targetN in iterableN]
"""
#Downgrade a two-dimensional list to a one-dimensional list
list = [col for row in matrix for col in row]
print(list)
# Corresponding for loop statement
list = []
for row in matrix:
    for col in row:
        list.append(col)
print(list)

"""
Advanced nested list comprehension
    Basic syntax: [express for target1 in iterable1 if condition1
                     for target2 in iterable2 if condition2
                           .....
                     for targetN in iterableN if conditionN]
"""
list = [[x, y] for x in range(5) if x % 2 == 0 for y in range(5) if y % 2 != 0]
print(list)
# Corresponding for loop writing method
_ = [] # Underscore indicates a temporary variable
for x in range(5):
    if x % 2 == 0:
        for y in range(5):
            if y % 2 != 0:
                _.append([x, y])
print(_)

Tuple

"""
Tuple is also a sequence
Tuples are represented using parentheses
But in fact, it works without parentheses, but it must be separated by commas
Tuples are immutable, so addition, deletion, modification, and search are only search operations, and no other operations are possible.
Other operations are basically the same as for lists (including slicing)
"""

Common operations on tuples

# Tuple definition
tuple = (1, 2, 3)
print(tuple)
tuple = 4, 5, 6
print(tuple)

# Generate a tuple with only one element (the key is to add a comma)
singleTuple = (1,)
print("Tuple of single element:", singleTuple)

# Get tuple elements using subscripts
print(tuple[0])
# Tuple slice
_ = tuple[:]
print(_)
print(_[::-1])

print("count method", tuple.count(5))
print("index method", tuple.index(5))

# The use of tuple plus and multiplication signs
t1 = (1, 2, 3)
t2 = (4, 5, 6)
print("Plus sign:", t1 + t2)
print("Multiply sign:", t1 * 2)

# Tuple nesting
t = t1, t2
print(t) # ((1, 2, 3), (4, 5, 6))
t = 1, 2, 3, (4, 5, 9)
print(t) # (1, 2, 3, (4, 5, 9))

# Iteration of tuples is omitted, same as list

# Use list comprehension for tuples (note: the result is still a list)
tuple = (1, 2, 3, 4)
list = [each * 2 for each in tuple]
print(list) # [2, 4, 6, 8]

Packaging and unpacking

"""
Packing and unpacking
    Packing: Generating a tuple is called tuple packing
    Unpacking: Assigning all elements of a tuple to other variables at once is called unpacking
        The number of variables must correspond to the number of elements of the tuple, otherwise an error will be reported
Packing and unpacking works not only for tuples, but also for any sequence type
"""
# Packing and unpacking of tuples
tuple = (1, 2, 3) # Pack
print(tuple)
a, b, c = tuple # unpack
print("a=", a, "b=", b, "c=", c)

# Packing and unpacking of lists
list = ["a", "b", "c"]
x, y, z = list
print(x, y, z)

# Packing and unpacking of strings
str = "123"
x, y, z = str
print(x, y, z)

# Python's multiple assignment,
#The implementation principle is to package and unpack through tuples
# _ = (10,20)
# x,y = _
x, y = 10, 20 # x = 10, y = 20
print(x)
print(y)

set collection

Brief introduction

"""
gather
    All elements in the set are unique and unordered
    Cannot be accessed by index
    The elements in the collection can only be immutable objects (such as strings and tuples), not mutable (such as lists)
"""
# Empty {} represents a dictionary
print(type({})) # <class 'dict'>
# {} represents a set when it has only one element and no colon
print(type({1})) # <class 'set'>
# {} has elements and a colon to indicate a dictionary
print(type({1:2})) # <class 'dict'>

set collection creation

"""
Collection creation
"""
# use {}
set1 = {1,2,3}
print(set1) # {1, 2, 3}
# Use set comprehensions
set2 = {k for k in "python"}
# The order of characters displayed and passed in may be inconsistent
print(set2) # {'p', 'y', 't', 'o', 'n', 'h'}
set3 = set("hello")
# Unrepeated and unordered
print(set3) # {'l', 'h', 'e', 'o'}

set collection built-in method

"""
Collection built-in methods
    copy(): shallow copy method
    isdisjoint():
        Checks whether there is no relationship between two sets and returns True if there is no relationship
        If some parts of the sets are the same, they are also considered to be related, and this method will return False
    issubset(parameter):
        Determine whether the set is a subset of the parameter set
    issuperset(parameter):
        Determine whether the set is a superset of the parameter set
    Calculate the union, intersection, difference, and symmetric difference of the current set and other objects.
"""
s = {"a", "b", "c"}
print(s.isdisjoint(set("aDWE"))) # False
print(s.isdisjoint("oython")) # True

# abc is a subset of abcdef
print(s.issubset("abcdef")) # True
print(s.issuperset("ab")) # True

# Union supports multiple parameters
print(s.union({1, 2, 3}))
print(s.union({1, 2, 3}, "hello"))

# Intersection supports multiple parameters
print(s.intersection({1, 2, "a"}))

# Difference set supports multiple parameters
print(s.difference({1, 2, 3}))

# Symmetric difference set does not support multiple parameters
print(s.symmetric_difference("ab123"))

# Operators can be used instead of functions
# When using an operator, both sides of the operator must be set types
# The function parameter can be a collection or an iterable object
# <= detect subset >= detect superset
print(s <= set("abcdfr"))
# <Detect true subset> Detect true superset
print(s < set("abcde"))
# |: Union & amp;: Intersection -: Difference ^: Symmetric difference

set set addition, deletion and modification operations

"""
Collections are divided into mutable collections and immutable collections
    Mutable collection: set
    Immutable collection: frozenset
    None of the above methods will change the contents of the collection, so both set and frozenset are suitable
"""

"""
Methods that only apply to set collections
Update collection:
    update(*others)
    intersection_update(*others) #Intersection
    difference_update(*others) # Difference set
    symmetric_difference_update(*others) # Symmetric difference set
Add elements:
    add (element to be added)
Delete elements:
    remove(element to be deleted) throws an exception if the element does not exist
    discard(element to be deleted) will not throw an exception if the element does not exist
    pop() randomly pops an element from the collection
    clear() clears the collection
"""
print("---------------")
s = {1, 2, 3}
print(s)
s.update(["a", "b"], "py") # It is actually the union_update() method. Union is omitted because it is used more.
print(s) # {1, 2, 3, 'a', 'y', 'p', 'b'}
s.intersection_update("123abc") # Intersection
print(s) # {'b', 'a'}
s.difference_update("123a") # Difference set
print(s) # {'b'}
s.symmetric_difference_update("12b") # Symmetric difference set
print(s) # {'2', '1'}

Built-in functions of sequences

Conversion between lists, tuples and strings

"""
Convert lists, tuples and strings to and from each other
    -- list() tuple() str()
"""
print(list("python")) # ['p', 'y', 't', 'h', 'o', 'n']
print(list((1, 2, 3, 4))) # [1, 2, 3, 4]

print(tuple("python")) # ('p', 'y', 't', 'h', 'o', 'n')
print(tuple([1, 2, 3, 4])) # (1, 2, 3, 4)

print(str(["python", "java"])) # ['python', 'java']
print(str((1, 2, 3, 4))) # (1, 2, 3, 4)

all(), any() methods

"""
max() min() sum() len() sorted() reversed()
sorted() returns a brand new list after sorting and does not change the original list
reversed() returns an iterator object
These functions are well-known by their names, so no examples will be given.

all():
    Determines whether all elements in an iterable object have true values
any():
    Determine whether the value of an element in an iterable object is true
"""
x = (1, 2, 0)
y = (1, 2, 3)
print(all(x)) # False
print(all(y)) # True

print(any(x)) # True
y = (0, 0, 0)
print(any(y)) # False

enumerate() method

"""
enumerate([start]):
    This function is used to return an enumeration object
    After converting the enumeration object into a list, it is a list of tuples
    Combine each element in the iterable object and the sequence number starting from 0 to form a tuple
    start: the value at which the custom serial number starts
"""
seasons = ["Spring", "Summer", "Fall", "Winter"]
print(enumerate(seasons)) # <enumerate object at 0x000002DC8528FD38>
# [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
print(list(enumerate(seasons)))
# [(10, 'Spring'), (11, 'Summer'), (12, 'Fall'), (13, 'Winter')]
print(list(enumerate(seasons, 10))

zip() method

"""
zip()
    Used to create an iterator that aggregates multiple iterable objects
    It will sequentially combine each element of each iterable object passed in as a tuple.
    i.e. the i-th tuple contains the i-th element from each iterable
    If the number of elements of the iterable object is inconsistent, the one with the smallest number of elements shall prevail.
"""
x = [1, 2, 3]
y = [4, 5, 6, 7]
z = [7, 8, 9, 10]
print(zip(x, y)) # <zip object at 0x000001D58CFD75C8>
print(list(zip(x, y))) # [(1, 4), (2, 5), (3, 6)]
# The part with a large number of parameters will be discarded
print(list(zip(x, y, z))) # [(1, 4, 7), (2, 5, 8), (3, 6, 9)]

# If you don't want to be discarded, use zip_longest() in the itertools module
import itertools

print(list(itertools.zip_longest(x, y, z))) # [(1, 4, 7), (2, 5, 8), (3, 6, 9), (None, 7, 10)] 

map() method

"""
map()
    Each element of the specified iterable object will be operated on according to the provided function.
    and return the operation result
    Returns an iterator
"""
# ord() returns the Unicode encoding corresponding to the character
print(ord("a")) # 97
print(map(ord, "abc")) # <map object at 0x000002049F5237F0>
# The ord() function requires one parameter, so the value provides an iterable object "abc"
print(list(map(ord, "abc"))) # [97, 98, 99]
# When the provided function requires multiple parameters, pass in the corresponding number of iterable objects.
# If the pow function requires two parameters, pass in two iterable objects
# Actually equal to finding 22, 33, 42
# If the number of elements in the two iterable objects is inconsistent, the smaller number shall prevail.
print(list(map(pow, [2, 3, 4], [2, 3, 2]))) # [4, 27, 16]

filter() method

"""
filter()
    Each element of the specified iterable object will be operated on according to the provided function.
    And return the element whose operation result is true in the form of an iterator
"""
print(list(filter(str.islower, "Python"))) # ['y', 't', 'h', 'o', 'n']