Python内置函数小总结

print(locals()) # 返回本地作用域中的所有名字

print(globals()) # 返回全局作用域中的所有名字

# 打开文件用print的file去打开

    f = open("file", 'a+', encoding='utf-8')

    print('内置函数', file=f)

    f.close()

# print的功能分割使用

    print(1, 2, 3, 4, sep='|')

# 模拟进度条算法:

    import time

    for i in range(0, 101, 2):

    time.sleep(0.1)

    char_num = i // 2

    per_str = '\r%s%% : %s\n' % (i, '*' * char_num) \

        if i == 100 else '\r%s%% : %s' % (i, '*' * char_num)

    print(per_str, end='', flush=True)

#列表去重 不用set去重,这样不会消耗内存

li = ['pig', 'pig', 'dog', 'cat', 'pikachu']

new_list = []

for line in li:

    if line not in new_list:

    new_list.append(line)

print(new_list)

# callable的使用 判断函数是否可用

    def x():

        pass

    print(callable(x))

# reversed迭代器对象 作用节省cpu

    x = [1, 2, 3, 4, 5]

    ret = reversed(x)

    print(ret.__next__())

# < 左对齐 > 右对齐 ^ 居中对齐

print(format('test', '>20'))

print(format('test', '^20'))

print(format('test', '<20'))

# bytes转换

print(bytes('你好', encoding='GBK').decode('GBK')) # unicode转换成GBK的bytes

print(bytes('你好', encoding='utf-8')) # unicode转换成utf-8的bytes

# 网络编程 只能传二进制数据

# 照片和视频也是以二进制存储

# html网页爬取到的也是编码

    ret = bytearray('你好', encoding='utf-8')  # 这是一个数组

    print(ret[0], ret)

# repr 和%r 原始输出

    print(type(repr('1')))# repr会把你输入的数据(包括符号)原封不动的输出,%r一样

    print(type(repr(2)))

    name ='egg'

    print('%s' % name)

    print('%r' % name)# %r会默认的加上''


# abs 绝对值运算(负数)

print(abs(-1))

# divmod 除法求余数

ret = divmod(7, 2)

print(ret, ret[1])

# round 按位取整

ret = round(3.14159, 3)

print(ret)

# pow幂运算ret = pow(2, 4)

print(ret)

# all 判断是否有bool值为False的值 只要里面有一个false就全部为false

print(all(['a', '', 123]))

print(all(['a', 12]))

print(bool(12))

# any 判断是否有bool值为True的值 要全部为假才能为假print(any(["", "123"]))

# zip函数返回要给迭代器x1 = [1, 2, 3]

x2 = ['a', 'b', 'c']

x3 = (['A'], 1, 'a',)

ret = zip(x1, x2, x3)

for i in ret:

    print(i)

# filter 过滤,并不是没有的代码它都能过滤

def is_odd(x):

        return x % 2 == 1

def is_str(s):

       return type(s) == str

def is_other(s):

        return s and str(s).strip()

# filter并不能直接得到答案 因为它是可迭代的__iter__

# ret = filter(is_odd, [1, 3, 5, 6, 2, 5])

# ret = filter(is_str, ["hello", "world", 1, 2, 3])

ret = filter(is_other, ["", '', " ", ' ', None, 1, 2, 3, 'a', 'b'])

for i in ret:

    print(i)

# map 会根据提供的函数对指定序列做映射

map函数语法:

    map(function, iterable, ...)

ret = map(abs, [1, 2, -4]) # 把列表的值每一个拿出去去执行abs

print(ret)

for i in ret:

    print(i)


# sort在原来的基础上进行排序

x1 = [-1,4, -10,3,7]

x1.sort(key=abs)

print(x1)

# sorted 生成了一个新的列表,不改变原列表 占内存

x2 = [-1,4, -10,3,7]

print(sorted(x2,reverse=True))

print(x2)

# sorted小练习

# 列表按照每一个元素的len排序

x3 = ['  ', [1,2],'HelloWorld']

print(sorted(x3,key=len))

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容