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

util中常用的集合函数:掌握集合类中的常用函数和其使用方法

发布时间:2023-05-20 06:46:11

Util包中有很多常用的集合函数。在这篇文章中,我将介绍一些常用的集合函数和它们的使用方法。

1. list()

list()函数是一个构造函数,用于创建一个新的列表。它可以接受任何可迭代对象,例如字符串、元组和集合。以下是使用list()函数创建列表的示例:

str = "abcd"
tup = (1, 2, 3, 4)
set = {5, 6, 7, 8}
lst1 = list(str)
lst2 = list(tup)
lst3 = list(set)
print(lst1)  # ['a', 'b', 'c', 'd']
print(lst2)  # [1, 2, 3, 4]
print(lst3)  # [8, 5, 6, 7]

2. len()

len()函数用于获取序列(列表、元组、字符串等)的长度。以下是len()函数的使用示例:

lst = [1, 2, 3, 4, 5, 6]
tup = (1, 2, 3, 4)
str = "hello"
print(len(lst))  # 6
print(len(tup))  # 4
print(len(str))  # 5

3. max()

max()函数用于获取序列中的最大值。以下为max()函数的使用方法:

lst = [1, 2, 3, 4, 5, 6]
tup = (1, 2, 3, 4)
str = "hello"
print(max(lst))  # 6
print(max(tup))  # 4
print(max(str))  # 'o'

4. min()

min()函数用于获取序列中的最小值。以下是min()函数的使用方法:

lst = [1, 2, 3, 4, 5, 6]
tup = (1, 2, 3, 4)
str = "hello"
print(min(lst))  # 1
print(min(tup))  # 1
print(min(str))  # 'e'

5. sorted()

sorted()函数用于对序列进行排序。默认情况下,它按升序排序。以下为sorted()函数的使用方法:

lst = [2, 1, 5, 3, 4]
tup = (4, 3, 2, 1)
str = "hello"
lst_sorted = sorted(lst)
tup_sorted = sorted(tup)
str_sorted = sorted(str)
print(lst_sorted)  # [1, 2, 3, 4, 5]
print(tup_sorted)  # [1, 2, 3, 4]
print(str_sorted)  # ['e', 'h', 'l', 'l', 'o']

6. sum()

sum()函数用于获取序列中所有元素的总和。以下为sum()函数的使用方法:

lst = [1, 2, 3, 4, 5]
tup = (1, 2, 3, 4)
print(sum(lst))  # 15
print(sum(tup))  # 10

7. any()

any()函数用于检查序列中是否有元素为True。以下为any()函数的使用方法:

lst1 = [0, "", False]
lst2 = [0, 1, 2]
print(any(lst1))  # False
print(any(lst2))  # True

8. all()

all()函数用于检查序列中的所有元素是否为True。以下为all()函数的使用方法:

lst1 = [0, "", False]
lst2 = [1, "hello", True]
print(all(lst1))  # False
print(all(lst2))  # True

9. zip()

zip()函数用于将多个列表合并成一个元组列表。以下为zip()函数的使用方法:

lst1 = [1, 2, 3]
lst2 = ["a", "b", "c"]
zipped = list(zip(lst1, lst2))
print(zipped)  # [(1, 'a'), (2, 'b'), (3, 'c')]

10. filter()

filter()函数用于过滤序列中不符合条件的元素。以下为filter()函数的使用方法:

lst = [1, 2, 3, 4, 5, 6]
def is_even(num):
    return num % 2 == 0
filtered_lst = list(filter(is_even, lst))
print(filtered_lst)  # [2, 4, 6]

总结

以上是一些常用的集合函数及其使用方法的介绍。这些函数可以大大提高代码的效率和可读性,因此在日常编程中经常用到。牢记这些函数,可以使您的编程过程更轻松。