Detailed summary: Python list knowledge points

WBOY
Release: 2022-11-23 20:42:14
forward
7266 people have browsed it

This article brings you relevant knowledge about Python, which mainly introduces some knowledge about lists, including creating lists, accessing list elements, and doing some research on the built-in functions and methods of lists. Organized, and finally there is a summary of knowledge about the list. Let’s take a look at it. I hope it will be helpful to everyone.

Detailed summary: Python list knowledge points

[Related recommendations: Python3 video tutorial]

Detailed explanation of Python built-in functions/methods—list list

A list is an orderedandchangeable collection, and is the most commonly used Python data type. In Python, lists are written using square brackets [].

1. Create a list

In Python, the data types of elements in the list can be different, and can include integers, floating point numbers, complex numbers, etc., of course, they can also contain Lists, tuples, dictionaries and sets, etc.

1.1 Use [ ] to create a list

To create a list, you only need to enclose different data items separated by commas using square brackets [] That’s it.

  • Createempty list
list0 = []
Copy after login
  • Createnon-empty list
list1 = ['Baidu', 'Alibaba', 'Tencent']
Copy after login

1.2 Use the list() function to create (convert to) a list

  • You can use the list() constructor to create a list:
this_list = list(('apple', 'banana', 'cherry'))
Copy after login

Note: When using the list() function to create a list, be sure to pay attention to the double brackets.

  • In Python, we can use the list() function to convert strings, tuples, dictionaries, and other similar objects such as sets into lists. For specific usage, see the built-in function below:

2. Access list

is the same as the list, we can use You can use index index to access an element in the list (get the value of an element), or you can use slicing to access a group of elements in the list (get a sublist).

2.1 Subscript index access

Subscript indexAccess tuples are divided into two categories, namely Forward index and Reverse index, the format is list_name[i], where list_name represents the list name, i represents the index value, i can be a positive number (forward index) or a negative number (inverted index).

It can be known that list_name[0] represents the first element of the list, and list_name[-1] represents the # of the list. ##Last element.

list_name = ['wzq', 'lgl', 'gz', 'whl', 'sj', 'hxw']print(list_name[0])print(list_name[-1])
Copy after login
wzq
hxw
Copy after login
Forward index: starting from the first (subscript 0), the second (subscript 1)...

Reverse index: starting from the last (first Subscript -1), second to last (subscript -2)...

2.2 Slice access

If you don’t understand the above description, you can Refer to the following table:

Tuple valuewzqlglgzwhl sjhxwForward index012345##Reverse Index

使用切片访问列表的格式为 list_name[strat : end : step] ,其中,start 表示起始索引,end 表示结束索引,step 表示步长。

list_name = ['wzq', 'lgl', 'gz', 'whl', 'sj', 'hxw']print(list_name[1:5:2])print(list_name[-6:-1:3])
Copy after login
['lgl', 'whl']['wzq', 'whl']
Copy after login

在使用切片访问列表元素时,list_name[strat : end : step],[start:end] 是左闭右开区间,即访问不了 end 代表的元素。

2.3 for 循环遍历列表

可以使用 for 循环遍历列表中的项目:

fruit_list = ['apple', 'pear', 'cherry']for i in fruit_list:
    print(i)
Copy after login
apple
pear
cherry
Copy after login

2.4 检查项目是否存在

要确定列表中是否存在指定的项,我们可以使用 in 关键字:

# 检查列表中是否存在'apple'fruit_list = ['apple', 'pear', 'cherry']print('apple' in fruit_list)
Copy after login
True
Copy after login

使用 in 关键字检查列表中是否存在指定项时,如果存在,则返回 True ;反之,则返回 False

2.5 更改列表值

当我们创建列表后,我们可以对列表中的数据项进行修改或更新,当然我们也可以使用 append() 方法来添加列表项。

fruit_list = ['apple', 'pear', 'cherry']fruit_list[2] = 'banana'print(fruit_list)
Copy after login
['apple', 'pear', 'banana']
Copy after login

注意:元组一旦创建后,其值将无法被更改,但是有其他解决方法。

2.6 列表连接(合并)/复制

与字符串一样,列表之间可以使用 + 号和 * 号实现元组的连接复制,这就意味着它们可以生成一个新的列表。

1、+连接(合并)

x = [1, 2, 3]y = [4, 5, 6]print(x + y)
Copy after login
[1, 2, 3, 4, 5, 6]
Copy after login

2、*复制

x = ['Hello']print(x * 5)
Copy after login
['Hello', 'Hello', 'Hello', 'Hello', 'Hello']
Copy after login

2.7 嵌套列表

使用嵌套列表即在列表里面创建其他列表。

x = [1, 2, 3]y = ['a', 'b', 'c']z = [x, y]print(z)
Copy after login
[[1, 2, 3], ['a', 'b', 'c']]
Copy after login

2.8 列表比较

列表比较需要引入 operator 模块的 eq 方法。

# 导入 operator 模块import operator

a = [1, 2]b = [2, 3]c = [2, 3]print("operator.eq(a, b):", operator.eq(a, b))print("operator.eq(b, c):", operator.eq(b, c))
Copy after login
operator.eq(a, b): Falseoperator.eq(b, c): True
Copy after login

3、内置函数

3.1 打印输出 print()

1、print()函数

print() 函数的功能我们已经非常熟悉了,就是打印输出。

my_list = ['pink', True, 1.78, 65]print(my_list)
Copy after login
['pink', True, 1.78, 65]
Copy after login

3.2 确定列表项目 len()

2、len()函数

当我们要确定一个列表有多少项目(元素)时,可以使用len()函数。

fruit_list = ['apple', 'banana', 'cherry']print(len(fruit_list))
Copy after login

3.3 返回变量类型 type()

3、type()函数

使用 type() 函数可以确定变量是什么类型(字符串、列表、元组、字典或集合)。

info_list = ['name', 'gender', 'age', 'height', 'weight']print(type(info_list))
Copy after login
<class 'list'>
Copy after login

当对info_list使用 type() 确定变量类型时,会返回<class 'list'>,表明这是一个列表

3.4 转换为列表 list()

4、tuple()函数

tuple() 函数的功能是,将其他类型转换为元组类型,详细用法如下:

  • 将字符串转换为列表
str1 = 'Hello Python'print(list(str1))
Copy after login
['H', 'e', 'l', 'l', 'o', ' ', 'P', 'y', 't', 'h', 'o', 'n']
Copy after login
  • 将元组转换为列表
tuple1 = ('Hello', 'Python')print(list(tuple1))
Copy after login
['Hello', 'Python']
Copy after login
  • 将字典转换为列表
dict1 = {'Hello': 'Python', 'name': 'pink'}print(list(dict1))
Copy after login
['Hello', 'name']
Copy after login
  • 将集合转换为列表
set1 = {'Hello', 'Python', 'name', 'pink'}print(list(set1))
Copy after login
['Python', 'name', 'pink', 'Hello']
Copy after login
  • 将区间转换为列表
range1 = range(1, 6)print(list(range1))
Copy after login
[1, 2, 3, 4, 5]
Copy after login

3.5 元组元素最大/小值 max()、min()

5、max()函数和min()函数

max() 函数的作用是返回列表中元素最大值min() 函数的作用是返回列表中元素最小值

list1 = [4, 6, 2, 0, -5]print(max(list1))print(min(list1))list2 = ['a', 'z', 'A', 'Z']print(max(list2))print(min(list2))
Copy after login
6-5z
A
Copy after login

3.6 删除列表 del

  • 删除单个元素

我们可以使用 del list_name[i] 来删除某个指定元素,其中 list_name 表示列表名,i 表示指定值的索引值。

list_de = ['Baidu', 'Alibaba', 'Tencent', 'Bytedance']del list_de[1]print(list_de)
Copy after login
['Baidu', 'Tencent', 'Bytedance']
Copy after login
  • 删除列表

del 函数不仅可以实现删除某个元素,还可以删除整个列表。

list_de = ['Baidu', 'Alibaba', 'Tencent', 'Bytedance']del list_de
Copy after login

当我们使用 del 函数删除某列表后,再使用 print() 函数打印输出时,会报错NameError: name 'list_de' is not defined,表明该列表未被定义。

4、内置方法

4.1 添加元素 append()、insert()、extend()

1、append()方法

append() 方法用于在列表末尾添加新的对象。

语法

list.append(element)
Copy after login

参数值

-6 -5 -4 -3 -2 -1
参数 描述
element 必需。任何类型(字符串、数字、对象等)的元素。

实例

  • 添加元素
fruit_list = ['apple', 'banana', 'cherry']fruit_list.append('pear')print(fruit_list)
Copy after login
['apple', 'banana', 'cherry', 'pear']
Copy after login
  • 添加列表
x = [1, 2, 3]y = ['A', 'B', 'C']x.append(y)print(x)
Copy after login
[1, 2, 3, ['A', 'B', 'C']]
Copy after login

2、insert()方法

insert() 方法用于将指定对象插入列表的指定位置。

语法

list.insert(position, element)
Copy after login

参数值

参数 描述
position 必需。数字,指定在哪个位置插入值。
element 必需。元素,任何类型(字符串、数字、对象等)。

实例

  • 把值 “orange” 作为第二个元素插入 fruits 列表:
fruits = ['apple', 'banana', 'cherry']fruits.insert(1, "orange")print(fruits)
Copy after login
['apple', 'orange', 'banana', 'cherry']
Copy after login
  • 将列表 y 插入到列表 x 中
x = [1, 2, 3]y = ['a', 'c']x.insert(0, y)print(x)
Copy after login
[['a', 'c'], 1, 2, 3]
Copy after login

append() 只能在末尾处添加元素或列表,insert() 可以在任意位置添加元素或列表。

3、extend()方法

extend() 方法用于在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)。

语法

list.extend(iterable)
Copy after login

参数值

参数 描述
iterable 必需。任何可迭代对象(列表、集合、元组等)。

实例

aver = ['A', 'B', 'C']
Copy after login
  • 添加字符串元素到列表末尾
str1 = 'Hello'aver.extend(str1)print(aver)
Copy after login
['A', 'B', 'C', 'H', 'e', 'l', 'l', 'o']
Copy after login
  • 添加列表元素到列表末尾
list1 = [1, 2, 3]aver.extend(list1)print(aver)
Copy after login
['A', 'B', 'C', 1, 2, 3]
Copy after login
Copy after login
Copy after login
  • 添加元组元素到列表末尾
tuple1 = (1, 2, 3)aver.extend(tuple1)print(aver)
Copy after login
['A', 'B', 'C', 1, 2, 3]
Copy after login
Copy after login
Copy after login
  • 添加字典元素到列表末尾
dict1 = {'name': 'pink', 'gender': True}aver.extend(dict1)print(aver)
Copy after login
['A', 'B', 'C', 'name', 'gender']
Copy after login
  • 添加集合元素到列表末尾
set1 = {1, 2, 3}aver.extend(set1)print(aver)
Copy after login
['A', 'B', 'C', 1, 2, 3]
Copy after login
Copy after login
Copy after login
  • 添加区间到列表末尾
range1 = range(1,10)aver.extend(range1)print(aver)
Copy after login
['A', 'B', 'C', 1, 2, 3, 4, 5, 6, 7, 8, 9]
Copy after login

4.2 元素出现次数 count()

count() 方法用于统计某个元素在列表中出现的次数。

语法

list.count(value)
Copy after login

参数值

参数 描述
value 必需。任何类型(字符串、数字、列表、元组等)。要搜索的值。

实例

num = [1, 4, 2, 9, 7, 8, 9, 3, 1]print(num.count(9))
Copy after login
2
Copy after login

4.3 指定值索引 index()

index() 方法用于从列表中找出某个值第一个匹配项的索引位置。

语法

list.index(element)
Copy after login

参数值

参数 描述
element 必需。任何类型(字符串、数字、列表等)。要搜索的值。

实例

num = [4, 55, 64, 32, 16, 32]print(num.index(32))
Copy after login
3
Copy after login

当被搜索值在列表中多次出现时,仅返回首次出现的位置。

4.4 对列表排序 sort()

sort() 方法用于对原列表进行排序,如果指定参数,则使用比较函数指定的比较函数。

语法

list.sort(reverse=True|False, key=myFunc)
Copy after login

参数值

参数 描述
reverse 可选。reverse=True 将对列表进行降序排序。默认是 reverse=False。
key 可选。指定排序标准的函数。

实例

  • 以字母顺序对列表进行排序:
words = ['Name', 'Gender', 'Age', 'Height', 'Weight']words.sort()print(words)
Copy after login
['Age', 'Gender', 'Height', 'Name', 'Weight']
Copy after login
  • 对列表进行降序排序:
words = ['Name', 'Gender', 'Age', 'Height', 'Weight']words.sort(reverse=True)print(words)
Copy after login
['Weight', 'Name', 'Height', 'Gender', 'Age']
Copy after login
  • 按照值的长度对列表进行排序:
# 返回值的长度的函数:def myfunc(e):
    return len(e)words = ['a', 'bb', 'ccc', 'dddd', '']words.sort(key=myfunc)print(words)
Copy after login
['', 'a', 'bb', 'ccc', 'dddd']
Copy after login
  • 根据字典的 “year” 值对字典列表进行排序:
# 返回 'year' 值的函数:def myfunc(e):
    return e['year']words = [
    {'char': 'a', 'year': 1963},
    {'char': 'b', 'year': 2010},
    {'char': 'c', 'year': 2019}]words.sort(key=myfunc)print(words)
Copy after login
[{'char': 'a', 'year': 1963}, {'char': 'b', 'year': 2010}, {'char': 'c', 'year': 2019}]
Copy after login
  • 按照值的长度对列表进行降序排序:
# 返回值的长度的函数:def myfunc(e):
    return len(e)words = ['aa', 'b', 'ccc', 'dddd']words.sort(reverse=True, key=myfunc)print(words)
Copy after login
['dddd', 'ccc', 'aa', 'b']
Copy after login
  • 指定列表中的元素排序来输出列表:
# 获取列表的第二个元素def takeSecond(elem):
    return elem[1]# 列表random = [(2, 2), (3, 4), (4, 1), (1, 3)]# 指定第二个元素排序random.sort(key=takeSecond)# 输出类别print('排序列表:', random)
Copy after login
排序列表: [(4, 1), (2, 2), (1, 3), (3, 4)]
Copy after login

4.5 复制列表 copy()

copy() 方法用于复制列表,类似于 a[:]

语法

list.copy()
Copy after login

参数值

无参数

实例

fruits = ['apple', 'banana', 'cherry', 'orange']x = fruits.copy()print(x)
Copy after login
['apple', 'banana', 'cherry', 'orange']
Copy after login

复制(制作副本)的另一种方法是使用内置函数 list() ,如下:

list1 = ['apple', 'banana', 'cherry']list_2 = list(list1)
Copy after login

4.6 颠倒列表顺序 reverse()

reverse() 方法用于反向列表中元素。

语法

list.reverse()
Copy after login

参数值

无参数

实例

fruits = ['apple', 'banana', 'cherry']fruits.reverse()print(fruits)
Copy after login
['cherry', 'banana', 'apple']
Copy after login

4.7 删除元素 pop()、remove()、clear()

1、pop()方法

pop() 方法用于移除列表中的一个元素(默认最后一个元素),并且返回该元素的值。

语法

list.pop(pos)
Copy after login

参数值

参数 描述
pos 可选。数字,指定需删除元素的位置。默认值 -1,返回最后的项目。

实例

  • pos 未指定时,默认删除最后的元素
fruits = ['apple', 'banana', 'cherry']fruits.pop()print(fruits)
Copy after login
['apple', 'banana']
Copy after login
  • pos 指定要删除元素的位置
fruits = ['apple', 'banana', 'cherry']fruits.pop(1)print(fruits)
Copy after login
['apple', 'cherry']
Copy after login

2、remove()方法

remove() 方法用于移除列表中某个值的第一个匹配项。

语法

list.remove(element)
Copy after login

参数值

参数 描述
element 必需。需删除的任何类型(字符串、数字、列表等)的元素。

实例

num = [1, 3, 2, 8, 3]num.remove(3)print(num)
Copy after login
[1, 2, 8, 3]
Copy after login

当被删除的元素在列表中存在多个时,默认删除首次出现的那个。

3、clear()方法

clear() 方法用于清空列表,类似于 del a[:]

语法

list.clear()
Copy after login

参数值

无参数

实例

word = ['A', 'B', 'C']word.clear()print(word)
Copy after login
[]
Copy after login

clear() 方法的作用是清空列表,执行结束后对其使用 printf() 打印输出时,会输出 [] ,说明列表还存在,只是空列表而已。

del 函数的作用是删除列表,执行结束后对其使用 printf() 打印输出时,会报错 NameError: name 'word' is not defined.

5、总结

函数 描述
print() 打印输出
len() 确定列表项目
type() 返回变量类型
list() 转换为列表
max() 返回列表元素最大值
min() 返回列表元素最小值
del 删除列表
方法 描述
append(obj) 在列表末尾添加新的对象
insert(index, obj) 在指定位置添加元素
extend(seq) 将列表元素(或任何可迭代的元素)添加到当前列表的末尾
count(obj) 统计某个元素在列表中出现的次数
index(obj) 返回具有指定值的第一个元素的索引
sort( key=None, reverse=False) 对原列表进行排序
copy() 复制列表
reverse() 颠倒列表的顺序
pop([-1]) 移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
remove(obj) 移除列表中某个值的第一个匹配项
clear() 清空列表

【相关推荐:Python3视频教程

The above is the detailed content of Detailed summary: Python list knowledge points. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!