好用的Python内置函数有哪些

发布时间:2022-05-24 09:54:54 作者:zzz
来源:亿速云 阅读:203

好用的Python内置函数有哪些

Python作为一种高级编程语言,以其简洁、易读和强大的功能而闻名。Python内置了许多实用的函数,这些函数可以帮助开发者更高效地完成任务。本文将介绍一些常用的Python内置函数,并解释它们的用途和用法。

1. len()

len()函数用于返回对象的长度或元素个数。它可以用于字符串、列表、元组、字典等数据类型。

s = "Hello, World!"
print(len(s))  # 输出: 13

lst = [1, 2, 3, 4, 5]
print(len(lst))  # 输出: 5

2. type()

type()函数用于返回对象的类型。它可以帮助开发者快速了解变量的数据类型。

x = 42
print(type(x))  # 输出: <class 'int'>

y = 3.14
print(type(y))  # 输出: <class 'float'>

3. range()

range()函数用于生成一个整数序列。它通常用于循环中。

for i in range(5):
    print(i)  # 输出: 0 1 2 3 4

range()函数还可以指定起始值、结束值和步长。

for i in range(1, 10, 2):
    print(i)  # 输出: 1 3 5 7 9

4. enumerate()

enumerate()函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标。

lst = ['a', 'b', 'c']
for index, value in enumerate(lst):
    print(index, value)
# 输出:
# 0 a
# 1 b
# 2 c

5. zip()

zip()函数用于将多个可迭代对象打包成一个元组序列。它通常用于同时遍历多个列表。

names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]

for name, age in zip(names, ages):
    print(name, age)
# 输出:
# Alice 25
# Bob 30
# Charlie 35

6. map()

map()函数用于将一个函数应用于一个或多个可迭代对象的每个元素,并返回一个迭代器。

def square(x):
    return x ** 2

numbers = [1, 2, 3, 4]
squared_numbers = map(square, numbers)
print(list(squared_numbers))  # 输出: [1, 4, 9, 16]

7. filter()

filter()函数用于过滤可迭代对象中的元素,返回一个迭代器。它接受一个函数和一个可迭代对象,函数用于测试每个元素,返回TrueFalse

def is_even(x):
    return x % 2 == 0

numbers = [1, 2, 3, 4, 5, 6]
even_numbers = filter(is_even, numbers)
print(list(even_numbers))  # 输出: [2, 4, 6]

8. sorted()

sorted()函数用于对可迭代对象进行排序,并返回一个新的列表。它可以接受一个key参数,用于指定排序的依据。

numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5]
sorted_numbers = sorted(numbers)
print(sorted_numbers)  # 输出: [1, 1, 2, 3, 4, 5, 5, 6, 9]

words = ['apple', 'banana', 'cherry']
sorted_words = sorted(words, key=len)
print(sorted_words)  # 输出: ['apple', 'cherry', 'banana']

9. all()any()

all()函数用于判断可迭代对象中的所有元素是否都为True,而any()函数用于判断可迭代对象中是否有任意一个元素为True

lst = [True, True, False]
print(all(lst))  # 输出: False
print(any(lst))  # 输出: True

10. sum()

sum()函数用于计算可迭代对象中所有元素的和。

numbers = [1, 2, 3, 4, 5]
total = sum(numbers)
print(total)  # 输出: 15

11. min()max()

min()函数用于返回可迭代对象中的最小值,而max()函数用于返回可迭代对象中的最大值。

numbers = [1, 2, 3, 4, 5]
print(min(numbers))  # 输出: 1
print(max(numbers))  # 输出: 5

12. abs()

abs()函数用于返回一个数的绝对值。

x = -10
print(abs(x))  # 输出: 10

13. round()

round()函数用于对浮点数进行四舍五入。

x = 3.14159
print(round(x, 2))  # 输出: 3.14

14. chr()ord()

chr()函数用于将整数转换为对应的ASCII字符,而ord()函数用于将字符转换为对应的ASCII码。

print(chr(65))  # 输出: 'A'
print(ord('A'))  # 输出: 65

15. isinstance()

isinstance()函数用于判断一个对象是否是一个已知的类型。

x = 42
print(isinstance(x, int))  # 输出: True
print(isinstance(x, str))  # 输出: False

16. id()

id()函数用于返回对象的唯一标识符(内存地址)。

x = 42
print(id(x))  # 输出: 140735680000000 (具体值取决于系统)

17. help()

help()函数用于查看对象的帮助文档。

help(len)
# 输出:
# Help on built-in function len in module builtins:
# len(obj, /)
#     Return the number of items in a container.

18. dir()

dir()函数用于返回对象的属性和方法列表。

print(dir(list))
# 输出:
# ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

19. eval()

eval()函数用于执行一个字符串表达式,并返回表达式的值。

x = 10
expression = "x * 2"
print(eval(expression))  # 输出: 20

20. exec()

exec()函数用于执行存储在字符串或文件中的Python代码。

code = """
x = 10
y = 20
print(x + y)
"""
exec(code)  # 输出: 30

21. format()

format()函数用于格式化字符串。它可以通过位置或关键字参数来替换字符串中的占位符。

name = "Alice"
age = 25
print("My name is {} and I am {} years old.".format(name, age))
# 输出: My name is Alice and I am 25 years old.

22. open()

open()函数用于打开文件,并返回一个文件对象。它可以用于读取、写入或追加文件内容。

with open('example.txt', 'r') as file:
    content = file.read()
    print(content)

23. input()

input()函数用于从用户输入中读取一行文本。

name = input("Enter your name: ")
print("Hello, " + name)

24. print()

print()函数用于将指定的内容输出到控制台。

print("Hello, World!")

25. repr()

repr()函数用于返回对象的字符串表示形式,通常用于调试。

x = 42
print(repr(x))  # 输出: '42'

26. hash()

hash()函数用于返回对象的哈希值。哈希值是一个整数,通常用于快速查找和比较。

x = "Hello"
print(hash(x))  # 输出: -727337308 (具体值取决于系统)

27. globals()locals()

globals()函数用于返回当前全局符号表的字典,而locals()函数用于返回当前局部符号表的字典。

x = 10
print(globals())
print(locals())

28. compile()

compile()函数用于将源代码编译为代码对象或AST对象。它可以用于动态执行代码。

code = compile('print("Hello, World!")', 'test', 'exec')
exec(code)  # 输出: Hello, World!

29. memoryview()

memoryview()函数用于返回一个内存视图对象,它允许直接访问对象的内存。

x = bytearray(b'Hello')
mv = memoryview(x)
print(mv[0])  # 输出: 72

30. property()

property()函数用于创建属性。它可以将方法转换为属性,使得访问属性时自动调用方法。

class Person:
    def __init__(self, name):
        self._name = name

    @property
    def name(self):
        return self._name

    @name.setter
    def name(self, value):
        self._name = value

p = Person("Alice")
print(p.name)  # 输出: Alice
p.name = "Bob"
print(p.name)  # 输出: Bob

31. staticmethod()classmethod()

staticmethod()函数用于创建静态方法,而classmethod()函数用于创建类方法。

class MyClass:
    @staticmethod
    def static_method():
        print("This is a static method.")

    @classmethod
    def class_method(cls):
        print("This is a class method.")

MyClass.static_method()  # 输出: This is a static method.
MyClass.class_method()  # 输出: This is a class method.

32. super()

super()函数用于调用父类的方法。它通常用于继承和多态。

class Parent:
    def __init__(self):
        print("Parent init")

class Child(Parent):
    def __init__(self):
        super().__init__()
        print("Child init")

c = Child()
# 输出:
# Parent init
# Child init

33. vars()

vars()函数用于返回对象的__dict__属性,通常用于查看对象的属性和值。

class MyClass:
    def __init__(self):
        self.x = 10
        self.y = 20

obj = MyClass()
print(vars(obj))  # 输出: {'x': 10, 'y': 20}

34. __import__()

__import__()函数用于动态导入模块。它通常用于在运行时导入模块。

math_module = __import__('math')
print(math_module.sqrt(16))  # 输出: 4.0

35. callable()

callable()函数用于判断一个对象是否是可调用的(如函数、方法、类等)。

def my_function():
    pass

print(callable(my_function))  # 输出: True
print(callable(42))  # 输出: False

36. hasattr(), getattr(), setattr(), delattr()

这些函数用于操作对象的属性。

class MyClass:
    def __init__(self):
        self.x = 10

obj = MyClass()
print(hasattr(obj, 'x'))  # 输出: True
print(getattr(obj, 'x'))  # 输出: 10
setattr(obj, 'y', 20)
print(obj.y)  # 输出: 20
delattr(obj, 'x')
print(hasattr(obj, 'x'))  # 输出: False

37. issubclass()

issubclass()函数用于判断一个类是否是另一个类的子类。

class Parent:
    pass

class Child(Parent):
    pass

print(issubclass(Child, Parent))  # 输出: True

38. next()

next()函数用于从迭代器中获取下一个元素。

numbers = iter([1, 2, 3])
print(next(numbers))  # 输出: 1
print(next(numbers))  # 输出: 2
print(next(numbers))  # 输出: 3

39. iter()

iter()函数用于返回一个迭代器对象。

numbers = [1, 2, 3]
iterator = iter(numbers)
print(next(iterator))  # 输出: 1
print(next(iterator))  # 输出: 2
print(next(iterator))  # 输出: 3

40. slice()

slice()函数用于创建一个切片对象,通常用于切片操作。

lst = [1, 2, 3, 4, 5]
s = slice(1, 4)
print(lst[s])  # 输出: [2, 3, 4]

41. reversed()

reversed()函数用于返回一个反转的迭代器。

lst = [1, 2, 3, 4, 5]
reversed_lst = reversed(lst)
print(list(reversed_lst))  # 输出: [5, 4, 3, 2, 1]

42. ascii()

ascii()函数用于返回对象的ASCII表示形式。

x = "Hello, 世界"
print(ascii(x))  # 输出: 'Hello, \u4e16\u754c'

43. bin(), oct(), hex()

这些函数用于将整数转换为二进制、八进制和十六进制字符串。

x = 42
print(bin(x))  # 输出: 0b101010
print(oct(x))  # 输出: 0o52
print(hex(x))  # 输出: 0x2a

44. bool()

bool()函数用于将对象转换为布尔值。

x = 0
print(bool(x))  # 输出: False

y = 1
print(bool(y))  # 输出: True

45. bytes()

bytes()函数用于将对象转换为字节序列。

s = "Hello"
b = bytes(s, 'utf-8')
print(b)  # 输出: b'Hello'

46. bytearray()

bytearray()函数用于创建一个可变的字节数组。

b = bytearray(b'Hello')
b[0] = 72
print(b)  # 输出: bytearray(b'Hello')

47. complex()

complex()函数用于创建一个复数。

c = complex(1, 2)
print(c)  # 输出: (1+2j)

48. float()

float()函数用于将对象转换为浮点数。

x = "3.14"
print(float(x))  # 输出: 3.14

49. int()

int()函数用于将对象转换为整数。

x = "42"
print(int(x))  # 输出: 42

50. str()

str()函数用于将对象转换为字符串。

x = 42
print(str(x))  # 输出: '42'

51. tuple()

tuple()函数用于将对象转换为元组。

lst = [1, 2, 3]
t = tuple(lst)
print(t)  # 输出: (1, 2, 3)

52. list()

list()函数用于将对象转换为列表。

t = (1, 2, 3)
lst = list(t)
print(lst)  # 输出: [1, 2, 3]

53. set()

set()函数用于将对象转换为集合。

lst = [1, 2, 2, 3]
s = set(lst)
print(s)  # 输出: {1, 2, 3}

54. frozenset()

frozenset()函数用于创建一个不可变的集合。

lst = [1, 2, 2, 3]
fs = frozenset(lst)
print(fs)  # 输出: frozenset({1, 2, 3})

55. dict()

dict()函数用于创建一个字典。

d = dict(a=1, b=2, c=3)
print(d)  # 输出: {'a': 1, 'b': 2, 'c': 3}
推荐阅读:
  1. Python这7个好用内置函数!
  2. python中的内置函数有哪些

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python

上一篇:在php中数组指针的操作函数有哪些

下一篇:php如何去掉数组中的空格元素

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》