前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >善用Python内置函数

善用Python内置函数

原创
作者头像
AIFEx
修改2023-10-07 19:41:31
3921
修改2023-10-07 19:41:31
举报
文章被收录于专栏:AIFEx的专栏AIFEx的专栏

0. 标题

善用Python内置函数

代码语言:txt
复制
作者: quantgalaxy@outlook.com   
blog: https://blog.csdn.net/quant_galaxy  
欢迎交流

1. 常用的内置函数介绍

1.1 pprint.pprint()

pprint.pprint() 能以自动格式化的方式打印复杂的数据结构。

可以对比下使用 print 和 pprint 这两种不同的效果:

代码语言:python
复制
# using print()
d = {
    'apple':[('juice',4),('pie',5)],
    'orange':[('juice',4),('cake',5)],
    'pear':[('whisky',6),('cake',7)]
}

print(d)

# {'apple': [('juice', 4), ('pie', 5)], 'orange': [('juice', 4), ('cake', 5)], 'pear': [('whisky', 6), ('cake', 7)]}
代码语言:python
复制
# using pprint()
d = {
    'apple':[('juice',4),('pie',5)],
    'orange':[('juice',4),('cake',5)],
    'pear':[('whisky',6),('cake',7)]
}

from pprint import pprint
pprint(d)

# {'apple': [('juice', 4), ('pie', 5)],
#  'orange': [('juice', 4), ('cake', 5)],
#  'pear': [('whisky', 6), ('cake', 7)]}

可以看到,pprint自动做了输出格式化,可以更方便的显示信息。

1.2 zip()

zip() 允许我们一次迭代 2 个或更多的东西,比如:

代码语言:python
复制
# without using zip
fruits = ['apple', 'orange', 'pear']
prices = [4,5,6]

for i in range(len(fruits)):
    fruit = fruits[i]
    price = prices[i]
    print(fruit, price)

# apple 4
# orange 5
# pear 6

如果使用zip,可以用更简洁的代码完成:

代码语言:python
复制
# using zip
fruits = ['apple', 'orange', 'pear']
prices = [4,5,6]

for fruit, price in zip(fruits, prices):
    print(fruit, price)

# apple 4
# orange 5
# pear 6

我们也可以一次迭代 3 件或更多事情,比如:

代码语言:python
复制
# using zip to iterate through 3 things at once
fruits = ['apple', 'orange', 'pear']
prices = [4,5,6]
stalls = ['A', 'B', 'C']

for fruit, price, stall in zip(fruits, prices, stalls):
    print(fruit, price, stall)

# apple 4 A
# orange 5 B
# pear 6 C

1.3 enumerate()

使用 enumerate() 迭代列表时,可以同时生成索引和元素,先来看自己实现这样的方式:

代码语言:python
复制
# without using enumerate()
fruits = ['apple', 'orange', 'pear']

for i in range(len(fruits)):
    fruit = fruits[i]
    print(i, fruit)

# 0 apple
# 1 orange
# 2 pear

如果使用 enumerate() 一行完成:

代码语言:python
复制
# using enumerate()
fruits = ['apple', 'orange', 'pear']

for i, fruit in enumerate(fruits):
  print(i, fruit)

# 0 apple
# 1 orange
# 2 pear
代码语言:txt
复制
作者: quantgalaxy@outlook.com   
blog: https://blog.csdn.net/quant_galaxy  
欢迎交流

1.4 dir()

dir() 函数返回对象的属性列表。

我们可以使用它来检查对象具有哪些方法或属性:

代码语言:shell
复制
>>> x = 1
>>> dir(x)
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__getstate__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'as_integer_ratio', 'bit_count', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'is_integer', 'numerator', 'real', 'to_bytes']

如果我们想快速检查某个对象具有哪些方法/属性,就会非常有用。

1.5 time.sleep()

sleep() 是暂停函数,可以暂停指定的秒,然后继续执行下面的语句。

支持浮点数,浮点数就是毫秒。

代码语言:python
复制
from time import sleep

sleep(5)     # our program sleeps for 5 seconds
sleep(10)    # our program sleeps for 10 seconds

1.6 sorted()

sorted() 可以排序list,并返回排序后的list:

代码语言:python
复制
fruits = [('apple',5),('orange',6),('pear',4)]

def condition(element):
  # this condition function makes the sorted() function
  # sort our elements by the second element
  # eg. the 5 in ('apple', 5)
  return element[1]

x = sorted(fruits, key=condition)
print(x)

# [('pear', 4), ('apple', 5), ('orange', 6)]

可以把 condition 函数,改为使用lambda表达式:

代码语言:python
复制
fruits = [('apple',5),('orange',6),('pear',4)]

x = sorted(fruits, key=lambda x:x[1])
print(x)

# [('pear', 4), ('apple', 5), ('orange', 6)]

lambda表达式我们单独写一篇文章介绍。

1.7 isinstance()

isinstance() 用户判断一个变量是否是一个类型的数据:

代码语言:python
复制
class Animal:
    pass

class Dog(Animal):
    pass

class GermanShepherd(Dog):
    pass

rocky = GermanShepherd()

print(isinstance(rocky, GermanShepherd))    # True
print(isinstance(rocky, Dog))               # True
print(isinstance(rocky, Animal))            # True
print(isinstance(rocky, object))            # True

1.8 os.listdir()

os.listdir() 允许我们遍历一个目录下的所有文件名,比如:

代码语言:python
复制
import os

print(os.listdir('test'))

# ['a.txt', 'b.txt', 'c.txt']

1.9 os.walk()

os.walk() 用于递归的遍历一个目录下的所有内容,返回包含三部分,当前目录,子目录,文件列表(root, subfolders, filenames),

root 是字符串类型,

subfolders 和 filenames 是 list 类型。

比如我们有一个目录结构如下:

代码语言:shell
复制
/test
  /subfolder1
    |- a.txt
  /subfolder2
    |= b.txt
    /subfolder3
      |- c.txt
  |- d.txt

我们使用 os.walk() 访问如下:

代码语言:python
复制
import os
for root, subfolders, filenames in os.walk('test'):
    print(root, subfolders, filenames)

# test ['subfolder2', 'subfolder1'] ['d.txt']
# test/subfolder2 ['subfolder3'] ['b.txt']
# test/subfolder2/subfolder3 [] ['c.txt']
# test/subfolder1 [] ['a.txt']

1.10 random.randrange()

返回一个随机数,半闭半开区间,[), 比如:

代码语言:python
复制
from random import randrange

x = randrange(1,11)
print(x)

# a number from 1 to 10 will be printed

随机函数有几种形式:

  • random.random(): 随机一个0, 1的浮点数
  • random.choice(iterable): 从可迭代元素中随机返回一个
  • random.sample(iterable, n): 从可迭代元素中返回n个元素

2. 作者信息

代码语言:txt
复制
作者: quantgalaxy@outlook.com   
blog: https://blog.csdn.net/quant_galaxy  
欢迎交流

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 0. 标题
  • 1. 常用的内置函数介绍
  • 1.1 pprint.pprint()
  • 1.2 zip()
  • 1.3 enumerate()
  • 1.4 dir()
  • 1.5 time.sleep()
  • 1.6 sorted()
  • 1.7 isinstance()
  • 1.8 os.listdir()
  • 1.9 os.walk()
  • 1.10 random.randrange()
  • 2. 作者信息
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档