Python's list, dictionary, set, tuple operations

foreword

We talked about some operations on strings earlier, but strings alone are far from enough. Here are some commonly used data storage methods

the list

In python, the role of the list is to store multiple data at one time, and it is a variable sequence. The operations we can perform on these data are: add, delete, modify, and check.

list creation

# 创建列表
# listname = []
# listname = list()
# 列表里储存着值
listdata = [1,2,3,4,5]

# 在python中可以用list()将range()转为列表
print(list(range(1,10)))

# 这样也可以
list_data = [i*10 for i in range(10)]
print(list_data)

List indexing and slicing

List indexing and slicing are the same as strings.

								正向索引
value value 1 value 2 value 3 value n
index 0 1 2 n-1
								反向索引
value value 1 value 2 value 3 value n
index -n -(n-1) -(n-2) -1

slice

# [start,end,step]
# start:起始值
# end:结束值
# step:步长 步长为正从右往左取值 步长为负冲左往右取值

list_data = list(range(1,10))


# 指定区间
print(list_data[2: 4]) # [3, 4]

# 指定步长
print(list_data[1: 4: 2]) # [2, 4]

# 取全部
print(list_data[:]) # [1, 2, 3, 4, 5, 6, 7, 8, 9]

# 步长为负
print(list_data[:2:-1]) # [9, 8, 7, 6, 5, 4]

CRUD

  • add element value to list

There are three ways to add element values ​​to a list.
The first is to add an element value to the end of the list.
The second is to add the entire list to the end of another list.
The third is to insert an element value at a specified position.

# 往列表末尾添加元素值
# listname.appen(obj) 会添加在列表的末尾
data = list(range(3)) # [0, 1, 2]
print(data.append(5)) # [0, 1, 2, 5]


# 将整个列表添加到另一个列表末尾
# listname.exten(seq)
data1 = list(range(3))  # [0, 1, 2]
data2 = list(range(4))  # [0, 1, 2, 3]
data1.extend(data2)
# 也可以将两个列表相加

# 往列表中插入元素值
# listname.insert(位置下标, 元素值)
data3 = list(range(4))  # [0, 1, 2, 3]
data3.insert(1, 10)  # [0, 10, 1, 2, 3]


  • Delete the value in the list
    There are two kinds of values ​​in the delete list,
    the first is to delete according to the index
    , and the second is to delete according to the element value
# 第一种 根据索引删除
# listname.pop(下标) 默认为最后一个 并返回删除的值
data1 = list(range(4))  # [0, 1, 2, 3]

# 默认为最后一个
data = data1.pop()  # 3
print(data1)  # [0, 1, 2]
data2 = data1.pop(1)  # 1
print(data1)  # [0, 2]


# 第二种 根据元素值删除 删除第一个匹配的数据
# 
data3 = list(range(10))  # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
data3.remove(2) # 返回值为None
print(data3)  # [0, 1, 3, 4, 5, 6, 7, 8, 9]


  • Modify the element value in the list
    can be modified according to the index value
data = list(range(10))  # 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
data[1] = 100
print(data)  # [0, 100, 200, 300, 4, 5, 6, 7, 8, 9]

# 切片也可以
data[2:4] = [200, 300]
print(data)  # [0, 100, 200, 300, 4, 5, 6, 7, 8, 9]

  • Find the element value in the list
    To find the element value in the list, you can use index() and count()

listname.index(obj)
Gets the position where the specified element value first appears, and returns the index of the element value.

# index()
data = list(range(1, 8)) # [1, 2, 3, 4, 5, 6, 7]
print(data.index(3))  # 3

# 指定的元素值如果不存在会报错
  • listname.count(obj)
    counts the number of occurrences of the specified element
# count() 
data = [1,2,4,5,2,1]
# 指定元素 1 出现的次数
print(data.count(1)) # 2

List sorting

sort() sorts the list and changes the original list together
reverse() reverses the entire list, such as [1,2,3], reversed to [3,2,1]
sorted() sorts the list to generate a new one The original list of the list is not changed

data = [1, 3, 4, 5, 2, 6]

# sort(key=None,reverse=False)
# key 指定排列规则
# reverse的值如果True则是降序排列 为False是升序排列 默认为False
data.sort(key=None, reverse=False)
print(data)

# 将列表颠倒过来
data.reverse()
print(data)



# 内置函数sorted()
data1 = [2, 4, 1, 3, 2, 5]
# 降序排列
new_list = sorted(data1, reverse=True)
print('原列表:', data1)
print('新列表:', new_list)

while for loops through the list

# while 
data = [2,4,51,2]
num = 0
# len()计算列表的长度
while num < len(data):
    print(data[num])
    num += 1

# for
for i in data:
    print(i)

list comprehension

What are list comprehensions? It is to use the for loop in the list to quickly generate a list that meets the requirements.

# 生成10的倍数 从0到100
data1 = [i*10 for i in range(11)]
print(data1)
# [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

# 现在有一个列表 我们需要剔除我们不需要的值,那怎们实现?
# 也可以用列表推导式
price = [1234,4555,2345,3445,9000,7565,7454,8656]
new = [i for i in price if i > 4000 ]
print(new) # [4555, 9000, 7565, 7454, 8656]

# 如果看起来有点懵 可以看下面这个 效果是一样的
price = [1234, 4555, 2345, 3445, 9000, 7565, 7454, 8656]
new = []
for i in price:
    if i > 4000:
        new.append(i)
print(new)        


list nesting

List nesting means that a list contains other data types.

data = [[1,2],[2,5,6],[2,3,45]]
# 同样是通过索引取值
print(data[0])
print(data[0][1])

# 还可以嵌套别的数据类型
data1 = [1,{
    
    's':1},3,[4,5]]

In the list, other data types are allowed to coexist, such as

listname = [1, 'str', 1.2, False]
print(type(listname[0])) # <class 'int'>
print(type(listname[1])) # <class 'str'>
print(type(listname[2])) # <class 'float'>
print(type(listname[3])) # <class 'bool'>

Append(), index(), remove(), len() are commonly used in the list, just check other methods when you need to use them.

tuple

We can use lists to store multiple data, and we can add, delete, modify and query these data, but what if we don't want these data to be modified? We can use tuples, which are used to store unmodifiable inner softness. There is not much difference between a tuple and a list. They are all indexed to find the value, and many methods can be shared.

Creation and deletion of tuples

# 创建元组
data1 = ('1','a','s')
# 用英文括号创建跟列表相似
# 注意如果元组中只有一个元素值,后面要加一个英文逗号
data2 = (1,)

# 我们可以用tuple()将range()转化为元组
data3 = tuple(range(3))
print(data3)


# 创建空元组
d = ()
d = tuple()

Common operations on tuples

Since tuples do not support modification, we can only lookup

  • index lookup
data = (1,2,5,5)
print(data[1]) # 2
  • len()
# 计算元组中的数据个数
data = (1,2,5,5)
print(len(data)) # 4
  • index()
# 跟列表一样 查找某个数据 并返回索引
data = (1,2,5,5)

re = data.index(2)
print(re) # 1
  • count()
# count()统计元素出现的次数
data = (1,2,5,5)
print(data.count(5)) # 2

dictionary

A dictionary is similar to a list and belongs to a variable sequence, but the dictionary is unordered, and the data in the dictionary is stored in the form of "key: value". Let's introduce it in detail.

create dictionary

# 创建控字典
data = {
    
    }
data1 = dict()
# 字典是以“ 键:值 ”形式存放值的
# 我们可以通过键来找到值,而且更好理解这值所代表的意义
# 在一个字典中键必须唯一,键可以是字符串/数值/元组/布尔类型, 不能是列表
# 字典取值
data2 = {
    
    'name':'天天','age':18,'weight':50}
# 这取值跟列表完成不同 字典是通过键来取值 而不是索引
print(data2['name'])}

Addition, deletion, modification and query of dictionaries

  • Increment
    syntax
    dictionary sequence[key] = value
data = {
    
    }
data['name'] = '天天'
print(data) # {'name': '天天'}
	
# 如果值早已存在 会被覆盖掉
data = {
    
    'name':2}
data['name'] = '天天'
print(data) # {'name': '天天'}


# update()
data1 = {
    
    'name': '天天'}
data2 = {
    
    'age': 18}
# 合并字典 update()
data1.update(data2)
print(data1)

	


  • delete
data1 = {
    
    'name': '天天', 'age': 18}

# del 指定键 删除字典中元素
del data1['name']
print(data1)
# pop 指定键 删除字典中元素
# pop del 是一样的 但是pop有返回值
data1.pop('age')
print(data1)

data = {
    
    'name': '天天', 'age': 18}
# clear() 删除字典中所有键值对
data.clear()
print(data)

  • Change
    syntax
    dictionary[key] = value
  • check

get()

# get(key,默认值)
# get() 通过键查找相应的值 如果没有就返回默认值None 默认值可以修改
data = {
    
    'name':'天天','age':18,'school':'ti'}
print(data.get('name'))
print(data.get('s','没有'))

keys()

data = {
    
    'name':'天天','age':18,'school':'ti'}
# 获取所有键
print(data.keys()) # dict_keys(['name', 'age', 'school'])
# 可以用list()转化为列表
print(list(data.keys()))

values()

data = {
    
    'name':'天天','age':18,'school':'ti'}
# 获取所有值
print(data.values()) # dict_values(['天天', 18, 'ti'])
# 可以用list()转化为列表
print(list(data.values()))

items()

data = {
    
    'name': '天天', 'age': 18, 'school': 'ti'}
# 获取所有键值对
print(data.items())  # dict_items([('name', '天天'), ('age', 18), ('school', 'ti')])
# 可以用list()转化为列表
print(list(data.items()))
# [('name', '天天'), ('age', 18), ('school', 'ti')]

loop over dictionary

data = {
    
    'name': '天天', 'age': 18, 'school': 'ti'}
# 遍历键
for i in data.keys():
    print(i)

# 遍历值
for k in data.values():
    print(k)

# 遍历键值对
# 返回的是一个元组(key,values) 可以用两个变量来接受
for key,values in data.items():
    print(key,values)

dictionary comprehension

We can use dictionary comprehension to quickly generate a dictionary, as follows



# i 表示键
# i * 2 表示值
data = {
    
    i: i * 2 for i in range(10)}
print(data)

# 将俩个列表合成为字典
data1 = ['name','age','fun']
data2 = ['天天501','18','game']
# 索引取值
data3 = {
    
    data1[i]:data2[i] for i in range(3)}
print(data3)



gather

The concept of a set is similar to that in mathematics. The elements in a set are not in order, all indexes are not supported, and the element values ​​are unique. The sets used are often used to store non-duplicate data or remove duplicate data.

collection creation

{}Use or to create a collection set(), but only if you want to create an empty collection set(), because {}it is used to create an empty dictionary.

# 创建集合
data = {
    
    'a','b'}

# 创建空集合
data1 = set()

Collection addition and deletion

  • Add to
data = {
    
    1,2,5}
# add() 添加数据
data.add(100)
print(data)


data1 = {
    
    1, 2, 5}
data2 = {
    
    1, 4, 5, 6}
# update() 合并集合 重复的数据会被去掉
data1.update(data2)
print(data1)

-delete

data = {
    
    1, 2, 5}
# remove()  删除指定的值 没有会报错
data.remove(5)
print(data)

# discard和remove() 差不多 没有值不会报错
data.discard(10)
print(data)
# 清空集合
data.clear()
print(data)

set comprehension



# i * 2 表示值
data = {
    
    i * 2 for i in range(10)}
print(data)
# {0, 2, 4, 6, 8, 10, 12, 14, 16, 18}

The difference between lists, tuples, dictionaries, sets

Before talking about their differences, let's talk about what is a variable sequence and an immutable sequence.
We know that we can call the value through the variable name. Every time we create a variable, the computer will allocate a memory address, which represents the location where the value is stored. as follows

data = 'a'
# id() 查询储存的地址
print(id(data))

Mutable and immutable sequences

There are six data types in python, lists, dictionaries, strings, sets, tuples, and numbers.
Among them, lists, dictionaries, and sets belong to mutable sequences, and numbers , tuples, and strings belong to immutable sequences .

  • Variable Sequence
    What is a variable sequence? That is, we can modify it but its original address will not change.
data = [2, 3, 4]

print('原来:', id(data))

data[1] = 10

print('修改后:',id(data))
  • Immutable sequence
    Immutable sequence means that if the value is modified, it will create a new address to store the modified value.
data = 123

print('原来:', id(data))

data = 124

print('修改后:',id(data))

The difference between lists, tuples, dictionaries, and collections. Collections and dictionaries do not support indexing, slicing, addition, and multiplication operations
insert image description here

Guess you like

Origin blog.csdn.net/qq_65898266/article/details/125012270