Object-oriented language (Python) - lists, tuples, dictionaries, sets in sequences


Flowers have a day of re-blooming, people are never young again

  Learn Python while you are young 


——Lungcen

 

Table of contents

 what is sequence

Sequence Properties - Index

Sequence Features - Slicing

 Sequence Concatenation - Adding

 Sequence Concatenation - Multiply

 checks if the element is contained in the sequence

 Sequence related built-in functions

 Python list (list)

 access list element

 Add elements to the list - (+)

  Add elements to the list - (append)

  Add elements to the list - (extend)

  Add elements to the list - (insert)

 delete list, delete list element

 list modification element

 list lookup element

 List implements stack and queue

Python tuples

Difference between (tuple) tuple and (list) list

 create tuple

 Access tuple elements

 Modify tuple, delete tuple

Python dictionary (dict)

(dict) Introduction to dictionaries

 create dictionary

access dictionary, delete dictionary

Basic operations on dictionaries

Add key-value pairs, modify key-value pairs, delete key-value pairs

Determine whether the specified key-value pair exists in the dictionary

 Get specific data in the dictionary

copy() method, setdefault() method

Python sets

Create a set collection

 access, delete collection, add element, delete element of collection



 what is sequence


The most widely used data type in Python is a sequence, which includes tuples, lists, sets, dictionaries, and strings

where the list is of mutable data type

Sequence Properties - Index

In the sequence, each element has its own number (index), starting from the starting element, and the index value increases from 0

It also supports negative index values. Such indexes are counted from right to left . In addition to starting from the beginning, the index of the sequence also supports counting from the last element, and the index value starts from -1

Sequence Features - Slicing

The slicing operation is another way to access elements in a sequence. It can access elements within a certain range. Through the slicing operation, a new sequence can be generated. However, it should be noted that these are head and tail

sname[start : end : step]

sname : indicates the name of the sequence

start : Indicates the start index position of the slice (including this position) . This parameter can also be left unspecified, and it will default to 0

end : Indicates the end index position of the slice (not including this position) , if not specified, it defaults to the length of the sequence

step : Indicates that during the slicing process, elements are fetched every few storage locations (including the current location), that is,

                       If the value of step is greater than 1, when slicing to sequence elements, elements will be "jumped"

str1 = '好好学习,天天向上'
print(str1[:2])  # 取索引区间为[0,2]之间(不包括索引2处的字符)的字符串
print(str1[::2])  # 隔 1 个字符取一个字符,区间是整个字符串
print(str1[:])  # 取整个字符串,此时 [] 中只需一个冒号即可
print(str1[1:7:2])  # 取从第一个(逻辑位置)到第六个(逻辑位置),并且两个一组选第二个

 Sequence Concatenation - Adding

Python supports the addition of two sequences of the same type using the "+" operator, which connects the two sequences but does not remove duplicate elements.

Capture keyword two sequences of the same type , we know that it needs to be of the same type and needs to be a sequence.

It cannot be a list + a string, because although the two are sequences, their types are not the same

It cannot be a value + a value, both of the same type, but not a sequence, so no connection will be performed

 Sequence Concatenation - Multiply

 Multiplying a sequence by the number n produces a new sequence whose contents are the result of repeating the original sequence n times.

str = '好好学习,天天向上'
print(str * 5) #可以输出五个str

 checks if the element is contained in the sequence

Use the in keyword  to check if an element is a member of a sequence

Use  the not in keyword to check whether an element is not contained in the specified sequence

str = 'www.baidu.com'
print("baidu" in str) #True
print("baidu" not in str) #False

 Sequence related built-in functions

 The more important of the related built-in functions are:

                len()、list()、str()、sorted()、reversed()、enumerate()

len(), you can get the length of the sequence and return how many elements there are in the sequence, often used in for loops

list(), converts a sequence to a list

str(), converts a sequence to a string

sorted(), sorts the elements in the sequence, but the returned value is a list (list)

        There is also a method sort to sort the list, this is to directly operate on the existing table, no return value

list1 = ['2', '1', '3']
tuple1 = ("2", "1")
dict1 = {"2": 2, "1": 1}
print(type(list1), list1)
print(type(tuple1), tuple1)
print(type(dict1), dict1)
list2 = sorted(list1)
tuple2 = sorted(tuple1)
dict2 = sorted(dict1)
print(list2)
print(tuple2)
print(dict2)

reversed(), the elements in the reverse sort sequence, that is, reverse sorting, the return value of this is an iterator

Since it is an iterator, it needs an iterable type to iterate it and output the elements in it.

        You can use list (list), tuple (tuple), collection (set)

        But you can't use a dictionary (dict), because you can't use dict() to convert it into a dictionary, and eval() can't convert an iterator into a dictionary, because eavl() requires the parameter to be a string

list1 = ['2', '1', '3']
tuple1 = ("2", "1")
dict1 = {"2": 2, "1": 1}
print(reversed(list1))
print(tuple(reversed(list1)))
print(list(reversed(list1)))
print(dict(reversed(list1))) # 这是错误的

enumerate(), combine the sequence into an index sequence, and return the enumeration object, which can be regarded as an iterator when it is used in the for loop . The content of the returned enumeration object is (element subscript, element value), which is similar to the content of the dictionary (key: value), so the dictionary can be used to receive the enumeration object.

list1 = ['2', '1', '3']
tuple1 = ("2", "1")
dict1 = {"2": 2, "1": 1}
print(list(enumerate(list1)))
print(tuple(enumerate(list1)))
print(dict(enumerate(list1)))
for i in enumerate(list1):
    print(i, end="  ")

There are some other built-in functions, among which are the maximum value, the minimum value, and one that can be summed . But in the sum() function, the parameters need to be all values, not other types.

str1 = '81576174091815'
print(max(str1))  # 找出最大的字符
print(min(str1))  # 找出最小的字符
list2 = [2, 1, 3]
print(sum(list2))
print(sum(list2, 4))  # 在前面列表计算总和后再加上4

 Python list (list)


 lt = ["Study hard, improve every day", 68, 3.14, [5, 3, 8], True]

A list can store any type of data such as integers, decimals, strings, lists, tuples, etc., and the types of elements in the same list can also be different. list refers to the list, because the data type of the list is list

1. Use [ ] to create a list

        You can assign a value in [ ], or you can not assign a value to empty

2. Use the list() function to create a list

        str = 'study hard, improve every day'

        print(list(str))

 access list element

A list is a type of Python sequence. We can use an index (Index) to access an element in the list (get the value of an element), or use a slice to access a set of elements in the list (get a new sublist)

str = 'http://www.baidu.com'
print(len(str)) # 得知str的长度
lt = list(str) # 将字符串转为列表
# 使用索引访问列表中的某个元素
print(lt[2]) 
print(lt[-20])
# 使用切片访问列表中的一组元素
print(lt[1:15])
print(lt[1:15:3])
print(lt[-20:-5:5])

 Add elements to the list - (+)

Multiple sequences can be concatenated using the + operator; a list is a type of sequence, so you can also use + to concatenate, which is equivalent to adding another list to the end of the first list.

list1 = [1, 2, 3, '好好学习']
list2 = ['天天向上',5, 6, 7]
list3 = list1 + list2
print(list1)
print(list2)
print(list3)

  Add elements to the list - (append)

The append() method is used to append elements at the end of the list . This method has no return value and is added on the existing basis

lt = ['你', '我', '他']
lt.append('它') # 追加元素
print(lt)
t = ('塔', '踏', '塌') # 追加元组,整个元组被当成一个元素
lt.append(t)
print(lt)
lt.append(['铊', '沓']) # 追加列表,整个列表也被当成一个元素
print(lt)

  Add elements to the list - (extend)

The difference between extend() and append() is that extend() does not treat the list or tuple as a whole, but adds the elements they contain to the list one by one.

If there is only one element added, such as adding "PTYTHON", it will be split into one by one, that is, 'P', 'Y', 'T', 'H', 'O', 'N'

If more than one element is added, such as adding ["PYTHON","python"], it will be split into two words instead of many letters one by one

lt = ['你', '我', '他']
lt.extend('它') # 追加元素
print(lt)
t = ('塔', '踏', '塌') # 追加元组
lt.extend(t)
print(lt)
lt.extend(['铊', '沓']) # 追加列表
print(lt)
lt.extend("PYTHON") # 它会将PYTHON拆'P', 'Y', 'T', 'H', 'O', 'N'
print(lt)

  Add elements to the list - (insert)

The append() and extend() methods can only insert elements at the end of the list. If you want to insert elements at a certain position in the middle of the list, you can use the insert() method.

When inserting a list or tuple, insert() will also treat them as a whole and insert them into the list as an element, which is the same as append().

lt = ['你', '我', '他']
lt.insert(1, "它") # 插入元素
print(lt)
tup = (1, "塔", 2) 
lt.insert(3, tup)# 插入元组,整个元祖被当成一个元素
print(lt) 
lt.insert(4, ["Hello", "World", 5, "好好学习"])# 插入列表,整个列表被当成一个元素
print(lt)
lt.insert(6, "天天向上") # 插入字符串,整个字符串被当成一个元素
print(lt)

The list connected by "+" is lt2 obtained by placing the elements in lt1 behind lt, so a new sequence will be generated, so lt2 is a regenerated list. ​​​​​​​​

Use extend to connect, this method has no return value, so the assignment (=) expression cannot be used. That is, extend must not be placed on the right side of the equation

Use append to connect, the function of this method is to append lt1 as an element to lt, which is completely different from the function of extend and "+"

 delete list, delete list element

For the list that has been created, if it is no longer used, you can use the del keyword to delete it

lt = [1, 2, 3, 4, 5, 6]
del lt[1] # 删除lt表中指定的位置
del lt[:] # 删除lt表中的全部数据
del lt # 删除lt

 The pop() method is used to delete the element at the specified index in the list

lt = ['你', '我', '他']
lt.pop() #如果不写 index 参数,默认会删除列表中的最后一个元素,类似于数据结构中的“出栈”操作。
print(lt)
lt.pop(1)# 使用pop函数弹出指定位置元素
print(lt)

 The remove() method , which will delete the element itself based on its value. It should be noted that the remove() method will only delete the first element with the same value as the specified value, and it must be ensured that the element exists, otherwise an error will be thrown. Under normal circumstances, use in to judge first (or use count() to count whether the element has appeared), and then use remove() to delete to prevent errors

clear() is used to delete all elements of the list, that is, to empty the list

lt = ['你', '我', '他']
lt.remove('你')
print(lt)
lt.clear()
print(lt)

 list modification element

It is very simple to modify a single element, just assign a value to the element directly.

Modify a range of values ​​with slice syntax

lt = ['你', '我', '他']
print(lt)
lt[0] = 'ta'
print(lt)
lt[0:2]=['tamen', 'women']
print(lt)
lt[1:1] = ['dd', 'mm', 'gg'] # 相当于插入一组新的元素
print(lt)
# lt[1:1] = 44 # 用切片语法赋值时,Python 不支持单个值
print(lt)
lt[2:2] = "444" # 每个字符都是一个元素,分割成了三个字符
print(lt)

 list lookup element

The index() method is used to find where an element appears in the list (that is, the index)

If the element does not exist, it will cause an error, so it is best to use the count() method to judge before searching.

listname.index(obj, start, end)

listname represents the list name,

obj represents the element to find,

start represents the starting position,

end indicates the end position.

The start and end parameters are used to specify the search range

        Both start and end can be omitted, and the entire list will be retrieved at this time

        If you only write start but not end, it means to retrieve the elements from start to the end

        If both start and end are written, it means to retrieve the elements between start and end.

lt = ['你', '我', '你', '他', '你', '他']
print(lt.index('你'))
print(lt.index('你', 1))
print(lt.index('你', 3, 5))

The count() method is used to count the number of times an element appears in the list

count() returns 0, which means that the element does not exist in the list, so count() can also be used to determine whether an element in the list exists.

lt = ['你', '我', '你', '他', '你', '他']
print(lt.count('你'))

 List implements stack and queue

Queues and stacks are two data structures, which store variables in a fixed order.

The difference between the two lies in the order in which the data is accessed:

                The queue is that the data stored first is taken out first, that is, "first in first out"

                The stack is that the last stored data is taken out first, that is, "last in, first out"

Considering that the storage of list type data itself is in order, and the internal elements can be of different types, it is very suitable for the implementation of queues and stacks.

 The implementation method of using the list list to simulate the queue function is to define a list variable

Use the insert() method when storing data , and set its first parameter to 0, which means inserting data from the front every time

When reading data, use the pop() method to pop the last element of the queue

In this way, the access order of data in the list list conforms to the characteristics of "first in, first out"

# 定义一个空列表充当队列,队列特点:先进先出
queue = []
# 元素入队
queue.insert(0, "好好学习")
queue.insert(0, 110)
queue.insert(0, "天天向上")
# 打印队列
print(queue)
# 取出队列元素
print(queue.pop())
print(queue.pop())
print(queue.pop())

The implementation method of using the list list to simulate the stack function is

                Use the append() method to store data

                Read data using the pop() method

When the append() method stores data into the list, it adds data at the end every time, which is just the opposite of the insert() method in the previous program.

# 创建一个空列表,充当栈,栈的特点:先进后出
stack = []
# 元素入栈,通过append函数添加
stack.append("好好学习")
stack.append("110")
stack.append("天天向上")
# 打印栈内容
print(stack)
# 元素出栈
print(stack.pop())
print(stack.pop())
print(stack.pop())

Python tuples


Difference between (tuple) tuple and (list) list

The differences between tuples and lists are:

The elements of the list can be changed, including modifying element values, deleting and inserting elements, so the list is a mutable sequence

Once a tuple is created, its elements cannot be changed , so a tuple is an immutable sequence .

All elements of the tuple are placed in a pair of parentheses ( ), and adjacent elements are separated by commas,

Tuples can store any type of data such as integers, real numbers, strings, lists, tuples, etc., and in the same tuple, the types of elements can be different

 create tuple

1) Use ( ) to directly create

        Tuples usually use a pair of parentheses to surround all elements, but the parentheses are not necessary, as long as the elements are separated by commas, Python will treat them as tuples

        One thing to note is that when there is only one element of string type in the created tuple, a comma must be added after the element, otherwise the Python interpreter will treat it as a string.

tuple1 = (1, 2, 3) # 合法的
tuple2 = ("好好学习", "天天向上") # 合法的
tuple3 = (1, 2, 3, 4, "好好学习", "天天向上", [5, 8, 6], ("Hello")) # 合法的
tuple4 = "Hello", 1, 3.14, [5, "Python"], (1, 5), "Java" # 合法的

# 当元素内容只有一个时不加逗号
tp1 = ("Hello")
print(type(tp1), tp1)
# 当元素内容只有一个时加上逗号
tp2 = ("Hello",)
print(type(tp2), tp2)

2) Use the tuple() function to create a tuple

str = "http://www.baidu.com"
tp1 = tuple(str) # 将字符串转换成元组
print(tp1)

lt = [1, 5, 9, "1", ["2", "3"]]
tp2 = tuple(lt) # 将列表转换成元组
print(tp2)

tp3 = tuple(str[2:8]) # 将区间转换成元组
print(tp3)

tp4 = tuple() # 创建空元组
print(tp4)

 Access tuple elements

Use the index (Index) to access an element in the tuple (get the value of an element)

You can also use slices to access a set of elements in a tuple (you get a new subtuple)

Similar to list (list)

 Modify tuple, delete tuple

A tuple is an immutable sequence, and elements in a tuple cannot be modified

But we can only create a new tuple to replace the old one

When the created tuple is no longer used, it can be deleted by the del keyword


Python dictionary (dict)


(dict) Introduction to dictionaries

A Python dictionary (dict) is an unordered, mutable sequence whose elements are stored in the form of "key-value pairs".

In contrast, lists (lists) and tuples (tuples) are ordered sequences , and their elements are stored next to each other at the bottom layer. The dictionary type is the only mapping type in Python.

"Mapping" is a term in mathematics. Simply understood, it refers to the corresponding relationship between elements, that is, through one element, another element can be uniquely found.

In dictionaries, it is customary to refer to the index corresponding to each element as a key, the element corresponding to each key as a value , and the key and its associated value as a "key-value pair".

read elements by key rather than by index The dictionary type is sometimes called an associative array or a hash table (hash). It associates a series of values ​​through keys, so that specific items can be retrieved from the dictionary by key, but not by index.
A dictionary is an unordered collection of arbitrary data types Unlike lists and tuples, the element corresponding to the index value 0 is usually called the first element, while the elements in the dictionary are unordered.
Dictionaries are mutable and can be nested arbitrarily A dictionary can be grown or shortened in place (no need to make a copy), and it supports nesting of any depth, that is, the value stored in the dictionary can also be a list or other dictionary.
Keys in the dictionary must be unique In the dictionary, the same key does not support multiple occurrences, otherwise only the last key-value pair will be kept.
The keys in the dictionary must be immutable The key of each key-value pair in the dictionary is immutable, and only numbers, strings or tuples can be used, and lists cannot be used.

 create dictionary

1) Use { } to create a dictionary

        Because each element in the dictionary contains two parts, namely the key (key) and the value (value), so when creating a dictionary, use a colon between the key and the value: to separate, and use commas to separate adjacent elements, all Elements are enclosed in braces { }.

# 使用字符串作为key
dict1 = {"k1":"val1", "k2":[1,"Hello"], "k3":("Python", 1991)}
print(dict1)
# 使用元组作为key
dict2 = {("好好学习", 2008):"天天向上", (1, "Python"):["天天向上", 2019]}
print(dict2)
# 创建空的字典
dict3 = {}
print(dict3)
dict1["dd"] = "wsdd"
print(dict1)

2) Create a dictionary through the fromkeys() method

        A dictionary with default values ​​can be created using the fromkeys() method provided by the dict dictionary type

# 创建列表
lt1 = [1, "Hello", ("好好学习", 2008)]
# 使用fromkeys函数创建字典
dt = dict.fromkeys(lt1, 2008)
print(dt)

3) Create a dictionary through the dict() mapping function

dict() function

# 通过 dict() 函数创建字典 a = dict(str1=value1, str2=value2, str3=value3)
dt1 = dict(Hello="人生苦短", 你好="Python")
print(dt1)
demo1 = [('two',2), ('one',1), ('three',3)]
demo2 = [['two',2], ['one',1], ['three',3]]
demo3 = (('two',2), ('one',1), ('three',3))
demo4 = (['two',2], ['one',1], ['three',3])
dt2 = dict(demo1)
print(dt2)
dt3 = dict(demo2)
print(dt3)
dt4 = dict(demo3)
print(dt4)
dt5 = dict(demo4)
print(dt5)

access dictionary, delete dictionary

Unlike lists and tuples, which access elements by subscript , dictionaries use keys to access corresponding values .

Because the elements in the dictionary are unordered, and the position of each element is not fixed, the dictionary cannot access multiple elements at once by slicing like lists and tuples.

Like deleting lists and tuples, manually deleting dictionaries can also use the del keyword. However, Python has its own garbage collection function, which will automatically destroy unused dictionaries, so it is generally not necessary to manually delete them through del.

dict1 = {"k1": "val1", "k2": [1, "Hello"], "k3": ("Python", 1991)}
val = dict1["k1"]
print(val)
# val = dict1["k4"] #若输入的key值不存在会报错
# print(val)
val = dict1.get("k1")
print(val)
val = dict1.get("k4")  # 若输入的key值不存在则会输出None
print(val)

Basic operations on dictionaries

Add key-value pairs, modify key-value pairs, delete key-value pairs

Add key-value pairs: dictname[key] = value       Description of each part: dictname represents the dictionary name. key represents the new key. value represents a new value , as long as it is a data type supported by Python.

Modify the key-value pair: the name of the key (key) in the Python dictionary cannot be modified, we can only modify the value (value).

The key of each element in the dictionary must be unique. Therefore, if the key of the newly added element is the same as the key of the existing element, the value corresponding to the key will be replaced by the new value , so as to achieve the purpose of modifying the element value .

Delete key-value pairs: del statement, del dt[ key ]

Determine whether the specified key-value pair exists in the dictionary

To determine whether a specified key-value pair exists in the dictionary, first determine whether there is a corresponding key in the dictionary . To determine whether the dictionary contains the key of the specified key-value pair, you can use the in or not in operator. The in or not in operator is judged based on the key.

dict1 = {"k1": "val1", "k2": [1, "Hello"], "k3": ("Python", 1991)}
print("k1" in dict1)
print("k2" not in dict1)

 Get specific data in the dictionary

The keys() method is used to return all the keys in the dictionary (key);

The values() method is used to return the values ​​(value) corresponding to all keys in the dictionary;

items() is used to return all key-value pairs (key-value) in the dictionary.

If you want to use the obtained data, you need to use the list() function to convert the data they return into a list

dict1 = {"k1": "val1", "k2": [1, "Hello"], "k3": ("Python", 1991)}
print(dict1.values())  # 获取values值
print(dict1.keys())  # 获取keys值
print(dict1.items())  # 遍历

values = dict1.values()  # 将类型转换为list
keys = dict1.keys()
items = dict1.items()

print(list(values))
print(list(keys))
print(list(items))

 Use a for in loop to iterate over their return values

dict1 = {"k1": "val1", "k2": [1, "Hello"], "k3": ("Python", 1991)}
for k in dict1:
    print(k, "->", dict1[k])
print("<----------->")  # dict1[k] 和 dict1.get(k))是一样的
for k in dict1:
    print(k, "->", dict1.get(k))
print("<----------->")
for k, v in dict1.items():
    print(k, "->", v)
    

copy() method, setdefault() method

The copy() method of the dictionary

dict1 = {"k1": "val1", "k2": [1, "Hello"], "k3": ("Python", 1991)}
dict2 = dict1.copy()
print(dict1)
print(dict2)

dict1["k4"] = "123"  # 添加新的元素不影响拷贝的
print(dict1)
print(dict2)

dict1["k2"].remove(1)  # 更改"k2"对应的地址中的值,则会影响拷贝的
print(dict1)  # 因为拷贝的"k2"中的内容是对应的地址值,不是对应地址的内容
print(dict2)

setdefault() 方法:dictname.setdefault(key, defaultvalue)

dictname indicates the dictionary name, key indicates the key, and defaultvalue indicates the default value (you can leave it blank, the default is None)

1. If the key exists, then directly return the value corresponding to the key

2. If the key does not exist, first set the default defaultvalue for the key

a = {'数学': 95, '语文': 89, '英语': 90}
print(a)
# key不存在,指定默认值
val = a.setdefault('物理', 100)
print(a)
# key不存在,不指定默认值
a.setdefault('化学')
print(a)
# key存在,指定默认值
a.setdefault('数学', 100)  # 已存在的返回原先的值
print(a)

Python sets


Create a set collection

1) Use {} to create

        setname = {element1,element2,...,elementn}

        Create an empty collection, cannot use setname = {}, this will be interpreted as dict (dictionary)

        Need to use setname = set(), this can create an empty collection

2) The set() function creates a collection

        The set() function is a built-in function of Python, and its function is to convert iterable objects such as strings, lists, tuples, and range objects into sets.

 access, delete collection, add element, delete element of collection

The elements in a collection are unordered, so you cannot use subscripts to access elements like a list.

Use the loop structure to read the data in the collection one by one.

a = {1, 2, 3, "2", 'qq', '3434'}
for e in a:
    print(e, end=' ')  # end是分隔符
print("\n<----->")
for e in a:
    print(e, end='-')

 The elements added using the add() method can only be numbers, strings, tuples, or Boolean (True and False) values, and variable data such as lists, dictionaries, and collections cannot be added

 To delete the specified element in the existing set collection, you can use the remove() method . Use this method to delete elements in the collection. It should be noted that if the deleted element is not included in the collection, this method will throw a KeyError error

Use the discard() method , which is exactly the same as the remove() method, the only difference is that this method will not throw any error when deleting an element in the collection fails

a = {1, 2, 3, "2", 'qq', '3434'}
a.remove('qq')
print(a)
a.discard('d')  # 这个不会报错
print(a)
a.remove('d')  # 这个会报错的

Flowers have a day of re-blooming, people are never young again

  Learn Python while you are young 


——Lungcen

Guess you like

Origin blog.csdn.net/qq_64552181/article/details/129678881