Advanced python list operation

1. Basic introduction to list

In Python, list is a very important and widely used data type that can store any number of ordered elements. The list can contain elements of different data types, such as integers, floating-point numbers, strings, etc., and elements can be added or deleted at any time, making it very flexible when dealing with dynamically changing data.

The following are some commonly used list operation functions and methods:

创建list: 通过在中括号内添加元素来创建

索引: 使用索引访问list中的单个元素,可以使用负数索引从末尾开始访问元素。

切片: 通过切片语法访问list中的连续子序列。

合并: 使用"+"运算符将两个list合并为一个新的list。

添加元素: 可以使用append()方法在list尾部添加一个元素,并使用insert()方法在指定位置插入一个元素。

删除元素: 可以使用remove()方法删除指定值的元素,或使用pop()方法删除指定索引位置的元素。

其他函数: len()函数返回list中元素的数量,sorted()函数按顺序返回list的副本。

2. List intersection and union

a = [1, 2, 3]

b = [2, 3, 4]

2.1 Intersection

2.1.1 Intersection writing method 1

list(set(a) & set(b))

[2, 3]

2.1.2 Intersection writing method 2

list(set(a).intersection(set(b)))

[2, 3]

2.2 Union

2.2.1 Union set writing method 1

list(set(a) | set(b))

[1, 2, 3, 4]

2.2.2 Union writing method 2

list(set(a).union(set(b)))

[1, 2, 3, 4]

2.3 Difference

list(set(a) ^ set(b))

[1, 4]

2.4 Batch modify the type of list elements

import numpy as np

dValue = [1, 5, 15, 25]
valueList = list(map(np.float64, dValue))
valueList 

[1.0, 5.0, 15.0, 25.0]

2.5 List inversion

a = range(1, 10)
list(a)

[1, 2, 3, 4, 5, 6, 7, 8, 9]

reversedA = reversed(a)
list(reversedA)

[9, 8, 7, 6, 5, 4, 3, 2, 1]

2.6 Locate the location of the element

cList = ['a', 'b', 'c']
cList.index('a')

Guess you like

Origin blog.csdn.net/programmer589/article/details/130308384