内置函数

怎么查看内置函数

dir(__builtins__)
序号 内置函数
a abs() aiter() all() any() anext() ascii()
b bin() bool() breakpoint() bytearray() bytes()
c callable() chr() classmethod() compile() complex()
d delattr() dict() dir() divmod()
e enumerate() eval() exec()
f filter() float() format() frozenset()
g getattr() globals()
h hasattr() hash() help() hex()
i id() input() int() isinstance() issubclass() iter()
l len() list() locals()
m map() max() memoryview() min()
n next()
o object() oct() open() ord()
p pow() print() property()
r range() repr() reversed() round()
s set() setattr() slice() sorted() staticmethod() str() sum() super()
t tuple() type()
v vars()
z zip()

abs()数字的绝对值

abs(-1)  # 1
abs(2)   # 2

aiter()异步迭代器

import asyncio

async def numbers(nums):
    for i in range(nums):
        yield i
        await asyncio.sleep(0.5)


# 隐式使用
[i async for i in numbers(10) if i % 2 == 0]
# 显式使用
[i async for i in aiter(numbers(10)) if i % 2 == 0]
# [0, 2, 4, 6, 8]

a = aiter(numbers(10))
dir(a)
'''
['__aiter__',
 '__anext__',
 '__class__',
...
'''

all()是否全为 True

all([1, False, True])  # False
all([1, "1", True])  # True

any()是否有 True 值

any([1, False, True])  # True
any([0, False, {}])    # False

anext()异步迭代下一项

import asyncio

class CustomAsyncIter:
    def __init__(self):
        self.iterator = iter(['A', 'B'])
    def __aiter__(self):
        return self
    async def __anext__(self):
        try:
            x = next(self.iterator)
        except StopIteration:
            raise StopAsyncIteration from None
        await asyncio.sleep(1)
        return x

async def main1():
    iter1 = CustomAsyncIter()
    print(await anext(iter1))       # Prints 'A'
    print(await anext(iter1))       # Prints 'B'
    print(await anext(iter1))       # Raises StopAsyncIteration

async def main2():
    iter1 = CustomAsyncIter()
    print('Before')                 # Prints 'Before'
    print(await anext(iter1, 'Z'))  # Silently terminates the script!!!
    print('After')                  # This never gets executed

asyncio.run(main1())
'''
A
B
raise StopAsyncIteration
'''

asyncio.run(main2())
'''
Before
A
After
'''

ascii()转为 ASCII 字符

ascii("小满")  # '\\u5c0f\\u6ee1'
a = "a"
n = 82
print(f"{a}的ascii码为:{ord(a)}")  # a的ascii码为:97
print(f"{n}对应的字符为:{chr(n)}")  # 82对应的字符为:R

bin()转为二进制字符串

bin(10)  # '0b1010'
bin(0o12)  # '0b1010'

bool()返回布尔值

bool(1)  # True
bool({})  # False

breakpoint()设置断点

# 语法如下:
# breakpoint(*args, **kws)
# 具体来说,它将调用 sys.breakpointhook(*args, **kws)
# sys.breakpointhook() 必须接受传递的任何参数,直接传递 args 和 kws。

bytearray()生成字节数组

name = "小满"

bytearray(name, encoding="utf-8")  # bytearray(b'\xe5\xb0\x8f\xe6\xbb\xa1')
list(bytearray(name, encoding="utf-8"))  # [229, 176, 143, 230, 187, 161]

bytes()生成字节序列

name = "小满"
bytes(name, encoding="utf-8")  # b'\xe5\xb0\x8f\xe6\xbb\xa1'

callable()对象是否可调用

def foo():
    pass

callable(foo)  # True

name = "小满"
callable(name)  # False

chr()Unicode 字符串

chr(122) # 'z'
chr(68)  # 'D'

classmethod()方法封装成类方法

from datetime import date

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

    @classmethod
    def fromBirthYear(cls, name, birthYear):
        return cls(name, date.today().year - birthYear)

    def display(self):
        print(f"{self.name}'s age is: {self.age}")


person = Person("eva", 17)
person.display()

person1 = Person.fromBirthYear("jack", 2000)
person1.display()

"""
eva's age is: 17
jack's age is: 23

在这里,我们有两个类实例创建者,一个构造函数和一个 fromBirthYear 方法。
构造函数采用常规参数 name 和 age。而 fromBirthYear 获取 class, name 和 birthYear,通过将当前年龄与当前年份相减来计算当前年龄,并返回类实例。
"""

compile()编译为代码对象

codeInString = 'a = 5\nb=6\nsum=a+b\nprint("sum =",sum)'
codeObejct = compile(codeInString, 'sumstring', 'exec')

exec(codeObejct)
# sum = 11

eval(codeObejct)
# sum = 11

complex()创建复数

complex('1-2j')
# (1-2j)

complex(-2j)
# (-0-2j)

delattr()删除对象属性

Python 的 delattr() 函数可以删除指定对象的指定属性。Python 提供了内置函数 setattr()、getattr()、delattr() 三个函数来分别设置、获取、删除对象的属性,让我们对对象属性的操作更新便利。

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

person = Person("小满", 3)
print(person.name) # 小满

delattr(person, "name")
person.name  # AttributeError: 'Person' object has no attribute 'name'


# 语法
delattr(obj, name, /)
# obj:要操作的对象,类或者实例
# name:属性名,是一个字符串
# 实参是一个对象和一个字符串。该字符串必须是对象的某个属性。返回 None。
# 如果对象允许,该函数将删除指定的属性。例如 delattr(x, 'foobar') 等价于 del x.foobar

dict()创建字典

# 以下示例创建的字典均等于
# {'name': '小满', 'age': 3, 'hobby': '摸鱼'}

d1 = dict(name="小满", age=3, hobby="摸鱼")
d2 = {'name': '小满', 'age': 3, 'hobby': '摸鱼'}
d3 = dict(zip(["name", "age", "hobby"], ["小满", 3, "摸鱼"]))
d4 = dict([("name", "小满"), ("age", 3), ("hobby", "摸鱼")])
d5 = dict({"age": 3, "hobby": "摸鱼", "name": "小满"})
d6 = dict({"name": "小满", "hobby": "摸鱼"}, age=3)

d1 == d2 == d3 == d4 == d5 == d6  # True

dir()对象的所有属性和方法

import os

name = "小满"

dir(name)
dir(os)

divmod()计算商和余数

divmod(16, 3)  # (5, 1)

enumerate()添加元素索引

nameList = ["小满", "大乔", "小乔"]
for index, name in enumerate(nameList, 1): # 第二个参数可以指定开始值
    print(index, name)

# 1 小满
# 2 大乔
# 3 小乔

nameList = ["小满", "大乔", "小乔"]
for index, name in enumerate(nameList):
    print(f"{name}的索引是{index}")
    
# 小满的索引是0
# 大乔的索引是1
# 小乔的索引是2

eval()执行字符串表达式

规避使用风险,应该慎用

eval('1+2')  # 3

a = 2
eval('a*4')  # 8

eval('[*"123"]')  # ['1', '2', '3']
eval('{"a":1}')  # {'a': 1}
eval('{"b": c}', {'c':10})  # {'b': 10}
eval('[i for i in range(2)]')  # [0, 1]

# linux系统中如果允许用户使用 eval(input()) 输入一个值,则用户可以使用命令:os 发出命令来更改文件,甚至删除所有文件:os.system('rm -rf *')。警告:千万别试啊!

# 返回值 是一个迭代器(filter 对象)

exec()执行复杂代码

exec("name='小满'\nprint(f'你好!{name}')")  # 你好!小满
exec("n=1+3-2")
n  # 2

filter()元素过滤

注:下面的代码是在jupyterlab下运行的

# 语法如下
filter(function, iterable)
# function - 测试 iterable 元素是否返回 true 或 false 的函数
# iterable - 要过滤的 iterable,可以是集合、列表、元组或任何迭代器的容器
# 如果 function 是 None ,则会假设它是一个身份函数,即 iterable 中所有返回假的元素会被移除。

[*filter(None, [1, False, 0, 3])]  # [1, 3]

# 求偶数案例
lst = [1, 2, 4, 5, -2, 8, 9]
res = filter(lambda x: x % 2==0, lst) 
print(res) # <filter object at 0x000002306DE7E380>
print(type(res))  # <class 'filter'>
print(list(res)) # [2, 4, -2, 8]

# 筛选大于5的值
[*filter(lambda x: x > 5, [2, 4, 7, 8, 9])]  # [7, 8, 9]

# 剔除指定英雄
heroList = ["小满", "小乔", "庄周", "大乔", "阿珂", "李白"]

def remove_hero(name):
    male_hero_list = ["李白", "庄周"]
    
    if name in male_hero_list:
        return False
    else:
        return True

[*filter(remove_hero, heroList)]  # ['小满', '小乔', '大乔', '阿珂']

float()构造浮点数对象

float(2) # 2.0
float("19.2")  # 19.2

format()格式化

参考之前都笔记 ^_^

frozenset()构建不可变集合

# 冻结的集合 frozenset
my_set = {1, 2, 3}
frozenset_set = frozenset(my_set)  # 冻结集合

my_set.add(9)
my_set  # {1, 2, 3, 9}

frozenset.add()  # 冻结住了不能操作相关方法
# AttributeError: type object 'frozenset' has no attribute 'add'

getattr()获取对象属性

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

person = Person("小满", 3, "摸鱼")

name = getattr(person, "name")
age = getattr(person, "age")
hobby = getattr(person, "hobby")

print(name)  # 小满
print(age)  # 3
print(hobby)  # 摸鱼

globals()全局变量

name = "小满"

globals()
"""
{'__name__': '__main__',
 '__doc__': 'Automatically created module for IPython interactive environment',
 '__package__': None,
 '__loader__': None,
 '__spec__': None,
 '__builtin__': <module 'builtins' (built-in)>,
 '__builtins__': <module 'builtins' (built-in)>,
 '_ih': ['', 'name = "小满"\n\nglobals()'],
"""

foo = 123
globals()[foo] = 456 # 456 修改
globals()["bar"] = 789 # 789 新增

hasattr()检测对象属性

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

person = Person("小满", 3, "摸鱼")
hasattr(person, "name")  # True

hash()对象的哈希值

一言以蔽之:可变类型不能被hash 能被hash都是不可变对象

hash("小满")  # -6459659841766706650
hash({4, 5, 6}) # TypeError: unhashable type: 'set'
hash([1, 2, 3])  # TypeError: unhashable type: 'list'
hash({}) # TypeError: unhashable type: 'dict'

help()内置帮助

import turtle

help(turtle) 
"""
Help on module turtle:

NAME
    turtle

MODULE REFERENCE
    https://docs.python.org/3.10/library/turtle.html
    
    The following documentation is automatically generated from the Python
    source files.  It may be incomplete, incorrect or include features that
    are considered implementation detail and may vary between Python
    implementations.  When in doubt, consult the module reference at the
    location listed above.
    ...更多略
"""
help(str)
help(dict)
# ....更多略

hex()16进制字符串

hex(88)  # '0x58'
hex(10086)  # '0x2766'

id()对象标识值

name = "小满"
id(name)  # 1308862378896

input()获取输入字符串

name = input("输入你的姓名:")
print(name)  

# 输入你的姓名: 小满
# 小满

int()构造整数

int(9.2)  # 9
int(True)  # 1
int("17")  # 17

isinstance()实例类型检测

name = "小满"

isinstance(name, str)  # True
isinstance(False, bool)  # True
isinstance({}, set)  # False
isinstance({}, dict)  # True

# 是否是其中的一个
isinstance(name, (set, str, list)) # True  
isinstance(name, set | str | list)  # True

class Foo():
    name = "小满"

class Bar(Foo):
    pass

foo = Foo()
isinstance(foo, Foo)  # True
isinstance(foo, Bar)  # False
isinstance(foo, object)  # True

class A:
    pass

class B(A):
    pass

isinstance(A(), A)    # True
type(A()) == A        # True
isinstance(B(), A)    # True
type(B()) == A        # False

issubclass()子类检测

# issubclass(class, classinfo) 主要用于判断参数 class 是否是类型参数 classinfo 的子类
from collections import abc

issubclass(str, str)  # True
issubclass(bool, int)  # True
issubclass(range, list)  # False
issubclass(range, abc.Sequence)  # True

iter()生成迭代器

heroList = ["小满", "小乔", "庄周", "大乔", "阿珂", "李白"]
name_iter = heroList.__iter__()

name_iter.__next__()  # "小满"
name_iter.__next__()  # '小乔'
# ...

heroList = ["小满", "小乔", "庄周", "大乔", "阿珂", "李白"]
name_iter = heroList.__iter__()

while True:
    try:
        print(next(name_iter))
    except StopIteration:
        break
"""
小满
小乔
庄周
大乔
阿珂
李白
"""

# 可以将 range() 对象转为迭代器:

it2 = iter(range(3))
next(it2) # 0
next(it2) # 1
next(it2) # 2
next(it2) # StopIteration 

len()对象长度

heroList = ["小满", "小乔", "庄周", "大乔", "阿珂", "李白"]
len(heroList)  # 

len("小满最棒啦")  # 5

heroDict = dict(name="小满", age=3, hobby="摸鱼")
len(heroDict)  # 3

list()创建列表

heroDict = {'name': '小满', 'age': 3, 'hobby': '摸鱼'}
list(heroDict)  # ['name', 'age', 'hobby']

list(range(1, 10, 2))  # [1, 3, 5, 7, 9] 
list("小满最棒啦")  # ['小', '满', '最', '棒', '啦']

locals()当前本地符号表的字典

def foo():
    name = "小满"
    age = 3
    
    def bar():
        hobby = "摸鱼"
    # 不建议调用局部字典的时候使用locals()
    print(f"locals() {locals()}")
    
foo()  # locals() {'name': '小满', 'age': 3, 'bar': <function foo.<locals>.bar at 0x00000130BFD812D0>}

map()对序列元素应用函数处理

注意:下面的代码是在jupyterlab中运行的

函数式编程在debug的时候,会很少受到循环的影响

数据越大,map函数的优势越大

# map() 函数的作用是将给定的函数应用于 iterable 的每一项(列表、元组等),并返回结果列表。
# 可以使用嵌入函数(内置函数)、lambda(拉姆达式、无名函数)、def 中定义的函数等应用到所有元素中。

# 参数
# function - 对可迭代的元素依次应用这个函数(可调用对象),函数的传入值是每个元素
# iterable - 要映射的可迭代对象,可以是多个序列

# 返回值
# 返回的结果是一个 map object(map 对象)的迭代器,可以将 map object 传递给 list()(创建列表)、set()(创建集合)等函数以显示和应用结果。

numbers = [1, 3, 5]

def foo(num):
    return pow(num, 2)

[*map(foo, numbers)]  # [1, 9, 25]

# 多个序列如果长度不一样,只会处理到最短的元素位置:
def add(x, y):
    return x + y

[*map(add, [1, 2, 3 ,4], [2, 3])]  # [3, 5]

# 有几个序列,函数就要承接几个参数:
ls = [1, 2, 3]
def foo(x, y, z):
    return x + y + z

[*map(foo, ls, ls, ls)]  # [3, 6, 9]

# =========函数式编程
# 里面的数字成2
# 常规方法1
data = [1, 2, 3, 4, 5, 6]
res = []
for index in data:
    res.append(index)
print(res)  # [2, 4, 6, 8, 10, 12]

# 常规方法2
res = [index * 2 for index in data]
print(res)  # [2, 4, 6, 8, 10, 12]
 
# 函数式编程
def doubled(n):
    return n * 2

res3 = map(doubled, data)
res3 = list(res3)
print(res3)  # 结果都是[2, 4, 6, 8, 10, 12]
# 案例1 摄氏度转华氏度
# 常规方法1
res1 = []

for item in data:
    new_item = item.copy() # 字典是可变的 先复制一份
    new_item["temp"] = item["temp"] * 9.0 / 5.0 + 32.0 #  确保结果都是小数
    res1.append(new_item)

for item in res1:
    print(item)
    
# 常规方法2
def c_to_f(item):
    new_item = item.copy()
    new_item["temp"] = new_item["temp"] * 9.0 / 5.0 + 32.0
    return new_item

res2 = [c_to_f(item) for item in data]
for item in res2:
    print(item)

# 使用map函数
res3 = map(c_to_f, data)
res3 = list(res3)
for item in res3:
    print(item)

# 结果都是一样的
"""
{'city': 'Beijing', 'temp': 69.44}
{'city': 'Changsha', 'temp': 72.32}
{'city': 'Chongqing', 'temp': 73.04}
{'city': 'Guangzhou', 'temp': 77.18}
{'city': 'Shanghai', 'temp': 68.54}
{'city': 'HongKong', 'temp': 78.62}
"""
# 案例2
# 注:代码是在jupyterlab下运行的, 可以直接使用%%time统计程序运行的时间
# 将50万个将数组化简,统计最终程序运行的结果,数组的第一个数字是分子,第二个是分母
import random

data = [(random.randint(1, 1000), random.randint(1, 1000)) for _ in range(50_0000)]
def gcd(a, b):
    # 求最大公约数的函数
    r = a % b
    while (r := a % b):
        a = b
        b = r
        r = a % b
    return b

def simplify(pair):
    # 化简数字的函数
    n1, n2 = pair
    m = gcd(n1, n2)
    return (int(n1/m), int(n2/m))


# 常规方法1
%%time
res1 = []
for pair in data:
    n1, n2 = pair
    m = gcd(n1, n2)
    res1.append((int(n1/m), int(n2/m)))
"""
CPU times: total: 250 ms
Wall time: 589 ms
"""

# 常规方法2
%%time
res2 = [simplify(pair) for pair in data]
"""
CPU times: total: 234 ms
Wall time: 510 ms
"""

# 使用map函数
%%time
res3 = map(simplify, data)
res3 = list(res3)
"""
CPU times: total: 203 ms
Wall time: 508 ms
"""

# map函数结合多进程
%%time
import os
from multiprocessing.dummy import Pool

with Pool(os.cpu_count()) as p:
    res4 = p.map(simplify, data)
    res4 = list(res4)

max()最大元素

max([1, 2, 4]) # 4
max([-1, 2])  # 2

memoryview()创建内存视图

v = memoryview(b'abcefg')
v[1]
# 98
v[-1]
# 103
v[1:4]
# <memory at 0x7f3ddc9f4350>
bytes(v[1:4])
# b'bce'

min()最小元素

min([1, 2, 4]) # 1
min([-1, 2])  # -1

next()迭代下一项

heroList = ["小满", "小乔", "庄周", "大乔", "阿珂", "李白"]
name_iter = heroList.__iter__()

name_iter.__next__()  # "小满"
name_iter.__next__()  # '小乔'
# ...

heroList = ["小满", "小乔", "庄周", "大乔", "阿珂", "李白"]
name_iter = heroList.__iter__()

while True:
    try:
        print(next(name_iter))
    except StopIteration:
        break
"""
小满
小乔
庄周
大乔
阿珂
李白
"""

# 可以将 range() 对象转为迭代器:

it2 = iter(range(3))
next(it2) # 0
next(it2) # 1
next(it2) # 2
next(it2) # StopIteration 

object()空对象

o = object()
# 它是 Python 中所有对象的基类,你看到和使用的一切最终都依赖于这个对象。
# 可以使用 object 创建完全唯一的标记值(哨兵值,Sentinel value),使用 is 和 not 进行测试,只有在给出确切的对象实例时才会返回 True。
>>> x = object()
>>> o = object()
>>> o is x
False
>>> o == x
False

oct()转为八进制字符串

oct(2)  # '0o2'
oct(100233)  # 0o303611

open()打开文件

f = open("1.txt", encoding="utf-8")
data = f.read()

print(data)
f.close()

"""
小满最棒啦!
小乔是大笨蛋!
"""

ord()Unicode 码位编号

ord("a")  # 97
ord("z")  # 122

pow()求n次幂

pow(2, 3) # 8
pow(2, 3, 3) # 2 相当于 2的3次方然后求余数

print()打印对象内容

print("欢迎来到小满的博客")  # 欢迎来到小满的博客

property()修饰方法

# 语法如下:

class property(fget=None, fset=None, fdel=None, doc=None)

# fget:用于获取属性值的函数
# fset:用于设置属性值的函数
# fdel:用于删除属性的函数
# doc:docstring,文档字符串

range()等差数列对象

list(range(10)) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

repr()打印形式字符串

# repr() 返回的有得于解释器读取的形式,string 格式,因此将 string 格式可以传给 eval() 进行执行。
# 如果我们使用 repr() 函数打印字符串,然后它会用一对引号打印,如果我们计算一个值,我们会得到比 str() 函数更精确的值。
n = 10
repr(n)  # '10'
eval(repr(n))  # 10

reversed()序列反向迭代器

numbers = [1, 3, -2, 5]
lst = list(reversed(numbers))
print(lst)  # [5, -2, 3, 1]

round()小数舍入

# 如果第三个十进制值大于或等于五,则将数字四舍五入到小数点后两位;否则,数字将向下舍入
round(1.2345, 2)
# 1.23

round(1.9876, 2)
# 1.99

round(3.14)
# 3

round(0.618)
# 1

set()创建集合对象

set("小满最棒啦")  # {'啦', '小', '最', '棒', '满'}
set([11, 11, 2, 3, 4, 3, 5, 7, 7])  # {2, 3, 4, 5, 7, 11}

setattr()设置对象属性

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

person = Person("小满", 3)
print(person.name)  # 小满

setattr(person, "name", "小乔")
print(person.name)  # 小乔

slice()切片对象

# Python 内置函数 slice() 返回一个切片对象
# 用于切取任何序列(字符串、元组、列表、range 或字节序列等)。

content = "欢迎来到小满的博客"
sliced = slice(4, 6)
content[sliced]  # '小满'

sliced = slice(2)
content[sliced]  # '欢迎'

sorted()返回已排序列表

content = "欢迎来到小满的博客"
sliced = slice(4, 6)
content[sliced]  # '小满'

sliced = slice(2)
content[sliced]  # '欢迎'

staticmethod()方法转换为静态方法

# Python 的内置函数 staticmethod() 是一个装饰器,它可以将一个方法封装为一个静态方法,该方法不强制要求传递参数。

class Calculator:
    @staticmethod
    def add_numbers(num1, num2):
        return num1 + num2

c = Calculator()

c.add_numbers(1, 2)
# 3

Calculator.add_numbers(2, 3)
# 5

str()对象的字符形式

str(True)  # 'True'

sum()求和

# sum() 的语法是:
sum(iterable, /, start=0)

# 参数:
#iterable:可迭代对象,如:列表、元组、集合,将会对这些数据进行相加或者连接
# start:起始值,保底值,从此值开始再加上序列中的所有值,默认为 0。

sum([1, 2, 5, 2])  # 10
sum([1, 2, 4], 3)  # 10
sum([])  # 0
sum([1, 2], start=1) # 4
sum([], 2)  # 2
sum(range(5))  # 10

sum({1: "a", 2: "b"})  # 3
sum({"a": 10, "b": 3}.values())  # 13
sum(([1, 2, 3], [4]), [])  # [1, 2, 3, 4]
sum([], ['a'])  # ['a']

# =======
# 因此,可以实现将一个二维(二元)列表转为一维列表(一元列表):
sum([[1,2],[3,4]], [])
# [1,2,3,4]

# 注意:但实际上你不应该那样做,因为那样做会很慢。

super()调用超类方法

# Python 的内置函数 super() 用于调用父类(超类)的一个方法,用来解决多重继承问题的。
# 不仅仅可以调用父类的构造函数,还可以调用父类的成员函数。
# super() 内置函数(对象)返回一个代理对象(超类的临时对象),允许我们访问基类的方法。

class Person:
    def kill(self, name, num):
        print(f"{name}已经抢了{num}个人头了")

class Hero(Person):
    def kill(self):
        super().kill("小满", 4)

xm = Hero()
xm.kill()
Hero.mro()

"""
小满已经抢了4个人头了
[__main__.Hero, __main__.Person, object]
"""

tuple()构建元组

tuple([1, 2, 3])  # (1, 2, 3)
tuple("小满最棒啦")  # ('小', '满', '最', '棒', '啦')
tuple({"name": "小满", "age": 3, "hubby": "摸鱼"}.values())  # ('小满', 3, '摸鱼')

type()对象的类型

name = "小满"
type(name)  # str

vars()对象属性字典

In [2]: vars()
Out[2]:
{'__name__': '__main__',
 '__doc__': 'Automatically created module for IPython interactive environment',
 '__package__': None,
 '__loader__': None,
 '__spec__': None,
 '__builtin__': <module 'builtins' (built-in)>,
 '__builtins__': <module 'builtins' (built-in)>,
 '_ih': ['', 'vars', 'vars()'],
 '_oh': {1: <function vars>},
 '_dh': [WindowsPath('C:/Users/chuxu')],
 'In': ['', 'vars', 'vars()'],
 'Out': {1: <function vars>},
 'get_ipython': <bound method InteractiveShell.get_ipython of <IPython.terminal.interactiveshell.TerminalInteractiveShell object at 0x000001F040EAB340>>,
 'exit': <IPython.core.autocall.ExitAutocall at 0x1f040eaab90>,
 'quit': <IPython.core.autocall.ExitAutocall at 0x1f040eaab90>,
 'open': <function io.open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)>,
 '_': <function vars>,
 '__': '',
 '___': '',
 '_i': 'vars',
 '_ii': '',
 '_iii': '',
 '_i1': 'vars',
 '_1': <function vars>,
 '_i2': 'vars()'}


bar = 1
vars()['bar']
# 1
'bar' in vars().keys()
# True

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

person = Person("小满", 3)
vars(person)  # {'name': '小满', 'age': 3}

zip()同位元素对象组合

# zip() 函数的语法为: zip(*iterables)
from itertools import zip_longest


heroList = ['小满', '大乔', "小乔"]
ageList = [3, 4]
dict(zip(heroList, ageList)) # {'小满': 3, '大乔': 4}
list(zip(heroList, ageList))  # [('小满', 3), ('大乔', 4)]

# 传入参数不齐,是按最短的数为准
heroList = ['小满', '大乔', "小乔"]
ageList = [3, 4]
dict(zip(heroList, ageList))  # {'小满': 3, '大乔': 4}
list(zip(heroList, ageList))  # [('小满', 3), ('大乔', 4)]

# 短板补齐
# 我们知道,如果传入的多个可迭代对的长度不相等,则取最短的进行对应
# 这类似于木桶效应的短板现象,如果想按最长的处理,不足的用 None 补足补齐
# 可以使用 itertools 中的 zip_longest 方法:
heroList = ['小满', '大乔', "小乔"]
ageList = [3, 4]
dict(zip_longest(heroList, ageList))  # {'小满': 3, '大乔': 4, '小乔': None}
# list(zip_longest(heroList, ageList))  # [('小满', 3), ('大乔', 4), ('小乔', None)]

# =======================
heroList = ['小满', '大乔']
ageList = [3, 4]
for name, age in zip(heroList, ageList):
    print(f"{name}{age}岁啦")
    
"""
小满3岁啦
大乔4岁啦
"""

### __import__导入模块

# 语法:
# __import__("模块名称")
# __import__("模块名称").模块方法

__import__("time").time()  # 1703595920.7320044
__import__("os").getcwd()  # 'E:\\小满'
__import__("os").system("pip list")
posted @ 2023-12-26 21:14  小满三岁啦  阅读(7)  评论(0编辑  收藏  举报