欢迎访问宙启技术站
智能推送

Python中的一些常用数据结构函数介绍

发布时间:2023-05-20 22:46:45

Python作为一种高级编程语言,为开发人员提供了许多用于数据结构和算法操作的内置函数。下面是一些Python的一些常用数据结构函数介绍。

## 列表

### append()

list.append(elem)

在列表的末尾添加一个新的元素。例如:

a = [1, 2, 3]
a.append(4)
print(a)

输出:

[1, 2, 3, 4]

### extend()

list.extend(seq)

在列表的末尾一次性追加另一个序列中的多个值。例如:

a = [1, 2, 3]
b = [4, 5, 6]
a.extend(b)
print(a)

输出:

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

### insert()

list.insert(index, elem)

将元素插入到列表的指定位置。例如:

a = [1, 2, 3]
a.insert(1, 4)
print(a)

输出:

[1, 4, 2, 3]

### remove()

list.remove(elem)

从列表中删除指定元素的 个匹配项。例如:

a = [1, 2, 3, 4]
a.remove(3)
print(a)

输出:

[1, 2, 4]

### pop()

list.pop([index])

移除列表中的一个元素(默认最后一个元素),并返回该元素的值。例如:

a = [1, 2, 3]
print(a.pop())
print(a)
print(a.pop(1))
print(a)

输出:

3
[1, 2]
2
[1]

## 元组

元组是不可更改的,因此不会有向列表一样的增加、删除或重新排序的函数。元组可以用来将一组相关的值放在一起处理并将它们传递给函数等。

### count()

tuple.count(elem)

统计元素在元组中出现的次数。例如:

a = (1, 2, 3, 2, 4)
print(a.count(2))

输出:

2

### index()

tuple.index(elem)

查找元素在元组中的位置。例如:

a = (1, 2, 3, 2, 4)
print(a.index(3))

输出:

2

## 字符串

### capitalize()

str.capitalize()

将字符串的 个字符大写化。例如:

s = "hello world"
print(s.capitalize())

输出:

Hello world

### find()

str.find(sub)

查找字符串中是否包含指定的子字符串,如果包含,则返回其 次出现的索引;否则返回-1。例如:

s = "hello world"
print(s.find("world"))

输出:

6

### join()

str.join(iterable)

连接字符串。例如:

s = " "
l = ["hello", "world"]
print(s.join(l))

输出:

hello world

## 字典

### clear()

dict.clear()

删除字典中的所有元素。例如:

d = {"a": 1, "b": 2}
d.clear()
print(d)

输出:

{}

### get()

dict.get(key[,default])

返回字典中key对应的value值,默认为None。例如:

d = {"a": 1, "b": 2}
print(d.get("a"))
print(d.get("c", 3))

输出:

1
3

### keys()

dict.keys()

返回字典中所有key的列表。例如:

d = {"a": 1, "b": 2}
print(d.keys())

输出:

dict_keys(['a', 'b'])

### values()

dict.values()

返回字典中所有value的列表。例如:

d = {"a": 1, "b": 2}
print(d.values())

输出:

dict_values([1, 2])

### items()

dict.items()

返回字典中所有元素的键值对元组列表。例如:

d = {"a": 1, "b": 2}
print(d.items())

输出:

dict_items([('a', 1), ('b', 2)])

## 集合

### add()

set.add(elem)

将元素elem添加到集合中。例如:

s = {1, 2, 3}
s.add(4)
print(s)

输出:

{1, 2, 3, 4}

### remove()

set.remove(elem)

将元素elem从集合中移除。如果元素不在集合中,则抛出KeyError异常。例如:

s = {1, 2, 3}
s.remove(2)
print(s)
s.remove(4)

输出:

{1, 3}
KeyError: 4

### pop()

set.pop()

随机移除并返回集合中的任意一个元素。如果集合为空,则抛出KeyError异常。例如:

s = {1, 2, 3}
print(s.pop())
print(s)

输出:

1
{2, 3}

### clear()

set.clear()

删除集合中的所有元素。例如:

s = {1, 2, 3}
s.clear()
print(s)

输出:

set()

以上是Python中一些常用的数据结构函数介绍,当然Python还提供了许多其他方便的数据结构函数,我们可以根据需要灵活运用。