Python container types--list, tuple, dict, set

Table of contents

1. list list

1. Definition of list

2.list features

2.1.list is an ordered collection of items

2.2.list is a variable data type

2.3.list can store any data type

3.Add, delete, modify and check lists

3.1.New addition to list

3.2. List operations

3.3.Deletion of list

3.4.Modification of list

4. Statistics

5.Copy of list

6.Reverse of list--reverse

7. Sorting of list--sort

8.List traversal

2. tuple tuple

1. Definition of tuple

2.Characteristics of tuple

2.1.Ordered project collection

2.2. Can store any data type

2.3. Immutable data types

3. dict dictionary

1.Characteristics of dict

1.1. Key-value mapping data structure key--value

1.2. Unordered item collection, no direct index

1.3. Variable data types

2.dict value

2.1. Use key to directly obtain the value

2.2. Use get to get the value

3. Dictionary traversal

4.Judge membership of dict

5.Deletion of dict

6.Merge of dict

7. Conversion between dict and str formats

4. set collection

1.Characteristics of set

1.1.set can be understood as a dictionary with only keys. All elements in it are unique and are inherently deduplicated.

1.2.Unordered item collection

1.3. Mutable data types, but the elements in the collection must be immutable data types

2.New addition to set

3.Deletion of set

4. Set operations

5. Interview related questions

The difference between lists and tuples

The difference between dictionary and collection


1. list list

1. Definition of list

#方式一
lst1 = []
print("method1:", type(lst1))
#方式二
lst2 = list()
print("method2:", type(lst2))

#list()为工厂函数,可以把其他数据类型转换为list
#若在list()中传递的是可迭代对象时,可挨个存入列表
lst3 = list("123abc")
print("lst3 is", lst3)

2.list features

2.1.list is an ordered collection of items

lst = ["a", "b", "c", "d", "e"]
#输出列表第2个元素
print(lst[1])
#lst[-1:2:-2] 其中-1为起始位置,2为结束位置(不包括),-2位步长
#正数表示从前往后 负数表示从后往前
print(lst[-1:2:-2])

2.2.list is a variable data type

Variable data types are in the original memory address space and can be modified.

lst = ["abc", "123"]
#id()内置函数返回对象的内存地址
print("the id before modifing is", id(lst))
#尝试直接修改原list,查看内存地址是否改变
lst[1] = "xxyy"
print("the id after modifing is", id(lst))

#如果直接修改不可变数据类型,会报错
#string为不可变数据类型
str1 = "abc"
try:
    #尝试修改str1的第1个元素
    str1[0] = "x"
    print("modify successful!")
except TypeError as err:
    print(err)

2.3.list can store any data type

#print表示存放内置函数
lst = ["a", 3.4, 4, [1], print]

3.Add, delete, modify and check lists

3.1.New addition to list

function concrete action
app() Append elements to the end of the list
insert() Insert element at specified position
extend() The elements passed in are iterable objects, and each element is inserted to the end in turn.
lst = ["aa", "12", "bb"]

lst.append("xxx")
print("after append:", lst)

lst.insert(2, "***")
print("after insert:", lst)

lst.extend("123")
print("after extend:", lst)

3.2. List operations

lst1 = [1, 2]
lst2 = [3, 4]
print("lst1 + lst2 =", lst1 + lst2)
print("lst1 * 3 =", lst1 * 3)

3.3.Deletion of list

function concrete action
pop()

The last element is deleted by default, or you can specify a subscript to delete it.

Can return deleted values

remove() Delete the specified element. If the element does not exist, an error will be reported.
del statement Delete slice
clear() Delete all elements
lst = ["a", "b", 1, 2, "c", "d"]

value = lst.pop()
print("delete the end of list:", lst)
print("the value of deleting:", value)
lst.pop(0)
print("delete the first of list:", lst)

try:
    lst.remove("d")
    print("delete success!")
except:
    print("delete fail!")

del lst[2:]
print("delect the a slice of list:", lst)

lst.clear()
print("delete all elements:", lst)

3.4.Modification of list

lst = ["a", "b", "c", "e", "f"]
#通过下标修改
lst[2] = "***"
print("after modifying by index:", lst)
#通过切片修改,赋值对象是一个可迭代对象
lst[3:] = "123"
print("after modifying by slice:", lst)

4. Statistics

function concrete action
len() The length of the statistics list
count()

Count the number of times a specified element appears in a list

index() Returns the subscript position of the specified element in the list. If there are multiple specified elements, returns the subscript of the first element.
lst = ["a", "a", "d", "d", "e"]
print("the length of list:", len(lst))
print("the count of a:", lst.count("a"))
try:
    print("the index of d:", lst.index("d"))
except ValueError as err:
    print(err)

5.Copy of list

If you directly use "lst2 = lst1" to copy, lst1 and lst2 point to the same object. If you change the value in lst2, it will also affect the value in lst1. You can use copy() to perform a shallow copy - only the copy type. value

lst1 = ["a", "b", "c", "d", "e", "f"]
lst2 = lst1.copy()

#修改lst2的值 不会对lst1产生影响
lst2[2] = "***"
print("lst1 is", lst1)
print("lst2 is", lst2)

#以切片的方式也可以实现浅拷贝
lst3 = lst1[:]
lst3[3] = "***"
print("lst1 is", lst1)
print("lst3 is", lst3)

6.Reverse of list--reverse

lst = ['a', 'b', 'c', 'd', 'e', 'f']
lst.reverse()
print("reverse list:", lst)

7. Sorting of list--sort

The sort method sorts the list in ascending order by default. If the elements in the list are numbers, they are sorted from small to large numbers. If the elements in the list are strings, they are sorted according to the sum of the Unicode codes of all characters in the string.

lst = ['f', 'e', 'd', 'c', 'b', 'a']
lst.sort()
print("asc:", lst)
#降序排序
lst.sort(reverse=True)
print("desc:", lst)

8.List traversal

lst = ["abc", "aa", "xx", "xyz"]

# 依次取列表中的元素
for i in lst:
    print(i)

# enumerate返回下标和值
print("key  -->     value")
for k, v in enumerate(lst):
    print(f"{k}    -->     {v}")

2. tuple tuple

1. Definition of tuple

t1 = ()
print(type(t1))

t2 = (1, )     #初始元组只有一个元素时,后面要打逗号,没有逗号为int类型
t3 = (1)
print(f"type of t2 is {type(t2)}, type of t3 is {type(t3)}")

2.Characteristics of tuple

2.1.Ordered project collection

2.2. Can store any data type

2.3. Immutable data types

The data in the tuple cannot be changed, but if the data you want to modify is of a variable type, then this element can be modified, such as: list, etc.

t1 = ("abc", 3, 4.5, [1, 2])
try:
    t1[0] = "a"
    print("modify success!", t1)
except TypeError as err:
    print(err)
# 修改tuple中存放的list类型的数据(可变数据类型)
try:
    t1[3][0] = 2
    print("modify success!", t1)
except TypeError as err:
    print(err)

3. dict dictionary

1.Characteristics of dict

1.1. Key-value mapping data structure key--value

The key of the dictionary is inherently deduplicated, and the key must be a hashable object (immutable data type)

The value of the dictionary can be any value

1.2. Unordered item collection, no direct index

1.3. Variable data types

2.dict value

2.1. Use key to directly obtain the value

d1 = {"name": "sumeng", "age": 18}
print(d1["name"])
# 没有想要获取的key值时会报错
try:
    print(d1["xxx"])
except:
    print("get error")

2.2. Use get to get the value

If the specified key cannot be found when getting the value of the get attribute, it will return None directly without reporting an error. Get can also set a default value.

d1 = {"a": 1, "b": 2}
print("the value of a is", d1.get("a"))
# 若字典key没有c,则返回0
print("the value of c is", d1.get("c", 0))

3. Dictionary traversal

d1 = {"a": 1, "b": 3}
# 直接进行循环遍历取值,取到的为key值
for i in d1:
    print(f"key is {i}")
# 使用items方法返回key和value
for i in d1.items():
    print(f"(key, value) is {i}")
for k, v in d1.items():
    print(f"{k} --> {v}")

4.Judge membership of dict

d1 = {"a": 1, "b": 3, "c": 5}

# 使用in关键字判断指定值是否在字典中--默认情况下判断的是key值
print("if a in d1:", "a" in d1)

# 使用values返回字典的所有value值
print(f"the values of dict is", d1.values())

# 使用keys返回字典中所有的key值
print(f"the keys of dict is", d1.keys())

5.Deletion of dict

d1 = {"a": 1, "b": 2, "c": 3}

# pop删除指定元素,返回指定删除key的values值
value1 = d1.pop("a")
print("deleted value is", value1)

# popitem删除存储的最后一个,返回被删除的(key, vlaue)元组
value2 = d1.popitem()
print("deleted (key, value) is", value2)

6.Merge of dict

d1 = {"a": 1, "b": 2}
d2 = {"c": 3, "d": 4}

# 直接改变的d1的内容,将d2合并到d1中去
d1.update(d2)
print(f"method1: {d1}")

# 合并生成新字典
d3 = dict(d1, **d2)
print(f"method2: {d3}")

7. Conversion between dict and str formats

Using JSON library

import json
d1 = {"zhangsan": {"age": 18, "hobby": "basketball"},
      "lisi": {"age": 18, "hobby": "music"}}

# dict --> str
d1_str = json.dumps(d1)
print(f"the type of d1_str is {type(d1_str)}")

# str --> dict
d2 = json.loads(d1_str)
print(f"the type of d2 is {type(d2)}")

4. set collection

1.Characteristics of set

1.1.set can be understood as a dictionary with only keys. All elements in it are unique and are inherently deduplicated.

This feature can be used for type conversion to achieve deduplication.

1.2.Unordered item collection

1.3. Mutable data types, but the elements in the collection must be immutable data types

2.New addition to set

s1 = {1, 2, 3}

# 新增1个元素
s1.add(4)
print(f"after add:", s1)

# 一次性新增多个元素update--传递可迭代对象
s1.update("abc")
print(f"after update:", s1)

3.Deletion of set

s1 = {1, 2, 3, 4, 'a', 'c', 'b'}

# 使用remove删除元素,若要删除的元素set中没有会报错
s1.remove(4)
print("after remove:", s1)

# 使用discard删除元素,要删除的元素不在set中也不会报错
s1.discard("x")
print("after discard:", s1)

4. Set operations

s1 = {1, 2, 3, 4}
s2 = {2, 4, 5, 6}

# 交集
print("s1 & s2 =", s1 & s2)
# 并集
print("s1 | s2 =", s1 | s2)
# 差集
print("s1 - s2 =", s1 - s2)
print("s2 - s1 =", s2 - s1)
# 对称差集--在s1、s2中,但不同时在两个里面
print("s1 ^ s2 =", s1 ^ s2)

5. Interview related questions

The difference between lists and tuples

1. The list is a variable data type and supports addition, deletion and modification operations. The tuple is an immutable data type and cannot be added, deleted and modified, and can only be replaced as a whole.

2. Since the list is a variable data type, it cannot be used as the key value of the dictionary, but the tuple can

3. When storing, an empty list takes up 16 bytes more than an empty tuple.

4. Use square brackets [] when defining a list, and use round brackets () when defining a tuple.

The difference between dictionary and collection

A dictionary is an unordered collection of keys and values.

A set is an unordered, unique set of elements without key and value pairs.

Guess you like

Origin blog.csdn.net/m0_69298614/article/details/132320020