python learning summary day8 tuples, dictionaries, sets

Posted by NightCoder on Thu, 18 Jun 2020 04:29:39 +0200

python learning summary day8 tuples, dictionaries, sets

1, Tuple

1. Tuple: a tuple is an immutable list and a container type of data. It does not support addition, deletion and modification, but only supports query (subscript operation).

  • 1) Empty tuple: () - > tuple

  • 2) Tuple of single element: (element,) - > tuple

tuple1 = (10)
print(tuple1,type(tuple1))  # 10 <class 'int'>

tuple2 = (10,)
print(tuple2,type(tuple2))	# (10,) <class 'tuple'>
  • 3) Tuples of multiple elements:
# a. Variable = (element 1, element 2, element 3,...)
tuple3 = (100, 200, 300)
print(tuple3, type(tuple3))    # (100, 200, 300) <class 'tuple'>

# b. Variable = element 1, element 2, element 3
tuple4 = 10, 20, 30, 40
print(tuple4, type(tuple4))    # (10, 20, 30, 40) <class 'tuple'>

2. Get the elements in the tuple

The way to get the elements is the same as the list. The operation of list query and tuple support

  1. Common subscript operations:
# a. Get single element
names = 'Garden baby', 'Spongebob', 'teletubbies', 'Digital Monster', 'Pocket Monster'
print(names[-1])  # Pocket Monster

# b. Slice
print(names[::2])    # ('garden baby', 'antenna baby', 'magic baby')

# c. Ergodic
for x in names:
    print(x)

for i in range(len(names)):
    print(names[i])

2) Unpacking:

# a. Variable 1, variable 2, variable 3,... = tuple
# Note: the number of variables should be consistent with the number of elements in the tuple
tuple1 = (10, 78, 45)
x, y, z = tuple1
print(x, y, z)    # 10 78 45

num1, num2 = 100, 200     # num1, num2 = (100, 200)

# b. Variable 1, variable 2, variable 3,... = tuple
# The number of previous variables is less than the number of tuples in the tuple, and there is only one variable before it*
person = ('Makabaka', 'Unidentified', 8, 100, 89, 50)
name, gender, age, *num = person
print(name, gender, age)   # Makabaka unknown 8
print(num)     # [100, 89, 50] returns a list

a, b, *c, d, e = 1, 2, 3, 4, 5, 6, 7, 8, 9     
print(a, b, c, d, e) # 1 2 [3, 4, 5, 6, 7] 8 9

# Add: unpacking function of *
list1 = [10, 20, 30]
print(*list1)    # 10 20 30   print(10, 20, 30)

2, Dictionary

Dictionary: a dictionary is also a container data type, with {} as its flag and elements separated by ','. Dictionary is unordered (ovo ~ does not support subscript operation), but variable data type (supports addition, deletion and modification)

1. Addition, deletion and modification of Dictionary:

#1. Add / change
"""
Syntax 1:
DICTIONARY [key] = value
 Key - > exist - > change the value corresponding to key to the specified value (change)
Key - > does not exist - > add a key value pair in the form of 'key: value' (increase)

Syntax 2:
Dictionary. SetDefault (key, value) - add key value pair (no modification)
"""
names = {'name': 'python', 'time': '2020-6-17'}
print(names) #{'name': 'python', 'time': '2020-6-17'}

#Change
names['time'] = '2021-6-17'
print(names) #{'name': 'python', 'time': '2021-6-17'}

#Increase
names['score'] = 9.0
print(names) # {'name': 'python', 'time': '2021-6-17', 'score': 9.0}

#Not modified
names.setdefault('score', 8.0)
print(names) # {'name': 'python', 'time': '2021-6-17', 'score': 9.0}

#Can be added
 names.setdefault('type ',' language ')
Print (names) {'name': 'Python', 'time': '2021-6-17', 'score': 9.0, 'type': 'language'}

#3. Delete
"""
1)del
 del DICTIONARY [key] - > delete the key value pair corresponding to the specified key (no error will be reported if the key does not exist)
"""
names = {'name': 'python', 'time': '2021-6-17', 'score': 9.0, 'type': 'language'}
del names['type '] (delete the whole key value pair of type)
print(names) 

"""
2)pop
 Dictionary. pop(key) - takes the value corresponding to the specified key in the dictionary and returns the retrieved value
"""
value = names.pop('type')
Print (names, value) {name ':'python', 'time':'2021-6-17 ',' score ': 9.0} language takes the value of type and returns

#4. Check
'''
1) DICTIONARY [subscript]

2) Dictionary. get('key ')
'''

2. Dictionary related functions and methods:

    1. Comparison operator: only = = - > to judge whether two dictionaries are equal
dict1 = {'name': 'qqj', 'age': 18}
dict2 = {'age': 18, 'name': 'qqj'}
print(dict1 == dict2)   # True
    1. In and not in

Data in dictionary > judge whether the key in the dictionary has the specified key

Data not in dictionary > judge whether the key in the dictionary does not exist the specified key

    1. Correlation function:
  • a. Len (Dictionary) - > count the number of key value pairs in the dictionary

  • b, Dict - > converts the specified data to a dictionary type
    Which can be converted - > 1. Container 2. The element in the data is a container with only two data. 3. The first element in the small container is an immutable data type

x = [(1, 2), (3, 4)]
print(dict(x))  # {1: 2, 3: 4}

y = ('ab', 'cd', 'xy')
print(dict(y))  # {'a': 'b', 'c': 'd', 'x': 'y'}
  • c. dictionary conversion to other types:
    Bool (Dictionary) - > empty dictionary will be converted to False, others are True
    List - > use all key s of the dictionary as the elements of the list
    Tuple - > use all key s in the dictionary as tuple elements
dog = {'name': 'Xiaobai', 'age': 2, 'color': 'black'}
print(list(dog)) # ['name', 'age', 'color']
  • d. fromkeys() method

    dict.fromkeys (sequence) - > create a new dictionary. The key of the dictionary is the element in the sequence and the value is None
    dict.fromkeys (sequence, value) - > create a new dictionary. The key of the dictionary is the element in the sequence, and the value is the specified value

stu = dict.fromkeys(['name', 'age', 'score'])

info = ['hape', 'ruizhi']
for i in info:
    new_info = stu.copy()
    new_info['name'] = i
    print(new_info) 
    # {'name': 'hape', 'age': None, 'score': None}
# {'name': 'ruizhi', 'age': None, 'score': None}
  • 4)items,keys,values
"""
Dictionary. Keys() - > get all key s in the dictionary and return a container (not a list)
Dictionary. Values() - > get all dictionary value s
 Dictionary. Item() - > get all key value pairs in the dictionary
"""
dog = {'name': 'small white', 'age': 2, 'color': 'Black'}
print(dog.keys())  # dict_keys(['name', 'age', 'color'])
print(dog.values())  # dict_values(['small white ', 2,' Black '])
print(dog.items())  # dict_items([('name ',' small white '), ('age', 2), ('color ',' Black ')])

3, Set

Set: the set is also a container type data type, with {} as its flag and elements separated by ','. Set is also unordered (ovo ~ does not support subscript operation), but variable data type (supports addition, deletion and modification)

1. Set: (the elements in the set are immutable and unique. )

# Empty set
empty = set()    # {} is an empty dictionary
# Non empty set
set1 = {1, 23, 34}
set2 = {(1, 2), 3, 4}
# set3 = {[1, 2], 3, 4}    # List cannot be an element of a collection
set4 = {1, 2, 3, 1, 4, 1}
print(set4)    # {1, 2, 3, 4}
print({1, 2, 3} == {2, 3, 1})   # True (description collection out of order)

2. Add, delete, modify and query elements in the set

# 1) Check
# There is no way for a collection to get a single element directly, it can only traverse random
"""
for variable in aggregate:
    //Circulatory body    
//Variable gets every element in the collection
"""
nums = {23, 34, 90, 89}
for x in nums:
    print(x)

# 2) Increase
"""
a. aggregate.add(element)   -  Add the specified element to the collection
b. aggregate.update(sequence)  -  Add all elements in the sequence to the collection
"""
nums.add(100)
print(nums)   # {34, 100, 23, 89, 90}

nums.update('abc')
print(nums)   # {34, 100, 'c', 'b', 23, 89, 90, 'a'}

nums = set()
nums.update({'a': 10, 'b': 20})
print(nums)    # {'a', 'b'}

# 3) Delete
"""
//Collection. Remove (element) - delete the specified element in the collection (the element does not exist and will report an error)
//Collection. Discard (element) - delete the specified element in the collection (the element does not exist and will not report an error)
"""
nums = {10, 89, 76, 90, 34}
# nums.remove(10)
nums.discard(10)
print(nums)

# nums.remove(100)  # report errors
nums.discard(100)   # No error

3. Mathematical set operation:

In python, sets support mathematical set operations: & (intersection), | (Union), - (subtraction), symmetric subtraction (^), > / < to determine whether they are true subsets

set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8, 9}

# 1) Intersection: finding the common part of two sets
print(set1 & set2)    # {4, 5}

# 2) Union: two sets merge into one set
print(set1 | set2)    # {1, 2, 3, 4, 5, 6, 7, 8, 9}

# 3) Difference set: Set 1 - Set 2 the rest of set 1 except for set 2
print(set1 - set2)   # {1, 2, 3}
print(set2 - set1)   # {8, 9, 6, 7}

# 4) Symmetric subtraction: remove the rest of the common parts of two sets
print(set1 ^ set2)   # {1, 2, 3, 6, 7, 8, 9}

# 5) True subset
# Set 1 > Set 2 - determine whether set 2 is the true subset of set 1
# Set 1 < set 2 - determine whether set 1 is the true subset of set 2
print({100, 200, 300, 400} > {10, 20})   # False
print({1, 10, 20} > {10, 20})    # True
print({10, 20} > {10, 20})       # False

4, Container comparison:

			   List tuple dictionary set
 Container flag [] () {} {}
Features: variable, ordered immutable, ordered variable, disordered variable, disordered
 Element not required no required key value pair (key immutable and unique) immutable, unique
 Add append, insert, extend / DICTIONARY [key] = value, setDefault add, update
 Delete del, pop, remove / pop, del remove, discard
 Change list [subscript] = value / DICTIONARY [key] = value/
Check to get a single element, slice, traverse the same list, single, traverse

Topics: Python REST less