python入门指南

复制代码
# -*- coding: gbk -*-
# 1. 到www.runoob.com/python/python或www.w3school.com.cn/python/index.asp学基本语法
# 2. 到这里(不定期更新)学中级语法,让程序更有python味。
# 3. 算法+数据结构=程序,语言是次要的。
# 4. 我水平不行,起个吓人的标题骗点击,sorry. [3,3]和(3,3)不等!
# https://www.cnblogs.com/wkkkkk/p/5731947.html 函数的命名参数
##########################  class etc ######################################
from functools import reduce
class HMS: # hour, minute, second. >>>help(staticmethod)
    def __init__(my, h = -1, m = 59, s = 59):
        my.d = 3 * [0]; my.hour = h; my.d[1] = m; my.d[2] = s
    def __str__(m):
        def dd(x): return str(x).rjust(2, '0') # >>>help(str)
        def DD(x): return str(('0'+str(x)))[-2:] # 11=>011=>11
        return reduce(lambda x,y:dd(x)+':'+DD(y), m.d)
    @property # >>>help(property)
    def hour(self): return self.d[0]
    @hour.setter
    def hour(m, h): m.d[0] = h if h >= 0 and h <= 12 else m.d[0]
    def __add__(a, b):
        def cncl(x): # canonical
            carry = 0
            while x >= 60: carry += 1; x -= 60
            # x=1,2 => x=(1,2)。不是C/C++里的逗号表达式
            return carry, x
        if not isinstance(b, HMS): return None
        print('%02d:%02d:%02d' % (b.d[0], b.d[1], b.d[2]), '', sep='|', end='')
        print(f'{b=}', b); c = HMS()
        for i in (0,1,2): c.d[i] = a.d[i] + b.d[i]
        for i in range(2,0,-1): (cy,c.d[i]) = cncl(c.d[i]); c.d[i-1] += cy
        return c
a = HMS(); a.hour = 9; s = 'a + HMS(1,2,3)'; print(s, '=', eval(s)); print()
############################################################################
try: raise Exception('没事')
except Exception as e: print(e.args)
print()
###########################  == is instanceof  #############################
class Num():
    def __init__(m, n = 0): m.n = n
    def __eq__(this, that): return isinstance(that, Num) and that.n == this.n
class Real(Num):
    def __init__(m, x = 0): Num.__init__(m, x)
def ec(x): print(x); exec(x, globals()) #  If only globals is given, locals defaults to it.
def el(x): print(x.ljust(20), eval(x))
ec('a = b = Num(); c = Num(); d = Real()')
el('a == b, a is b')
el('a == c, a is c')
el('3 == c, 3 is c')
el('type(a) is Num')
el('type(d) is Num')
el('c == d, d == c'); print()
###########################  list & dict comprehension  ####################
x = list('0123456789')
x = [i for i in x if i > '3'] # ord(), chr()
x = list(map(lambda i:ord(i), x))
print(x); print()
def lr(start, stop, step=1): return list(range(start, stop, step))
d = {}
for k in lr(0,10)+lr(1,5) + lr(3,7): d[k] = d.get(k, 0) + 1
d = {k:v for k,v in d.items() if v > 1}
print(d)
for k,v in sorted(d.items(), key=lambda kv:kv[1], reverse=1): print(v, k)
print()
##########################  decorator  #####################################
def time_it(func):
    def _(*args, **kwargs):
        import time
        print(str(func).split()[1], '('+func.__doc__+')', 'is running')
        t = time.perf_counter(); r = func(*args, **kwargs)
        t = time.perf_counter() - t
        print(round(t, 3), 'seconds') # print('%.4f' % t)
        return r
    return _
import random
@time_it
def monte_carlo_pi(nsamples):
    '''No documentation'''
    acc = 0
    for i in range(nsamples):
        x = random.random(); y = random.random()
        if (x ** 2 + y ** 2) < 1.0: acc += 1
    return 4.0 * acc / nsamples
print(monte_carlo_pi(1<<15)); print()
#############################  generator  ##################################
def permute(x):
    def pmt(x, y, n, i):
        if i == n: yield y
        for j in range(n):
            if x[j] < 0: continue
            y[i] = s = x[j]; x[j] = -1
            yield from pmt(x, y, n, i + 1)
            x[j] = s
    n = len(x)
    return pmt(x, list(range(n)), n, 0) 
for p in permute([1,2,3]): print(p)
print()
############################  deepcopy  ####################################
from copy import deepcopy
def get_list(n, v): return list(map(lambda _:v, range(n)))
def get_list_dc(n, v): return list(map(lambda _:deepcopy(v), range(n)))
x = get_list(2, get_list(2, 0)); y = get_list_dc(2, get_list_dc(2, 0))
x[0][0] = y[0][0] = -1; print(x, y, '\n')
############################  regular expression  ####################################
import re
print(re.split('[0-9 ]','a0bb1ccc d'), '\n') # str.splitlines()
############################  os & sys  ####################################
import os
import sys
import msvcrt
print(len(sys.argv), sys.argv); 
print('Press any key\r', end=''); msvcrt.getch(); os.system('color f1')
input('Press Enter  \r'); os.system('color')
# 本该恢复颜色的,不是我的锅, 请自行输入color<Enter>
复制代码

comprehension不是python首创

posted @   Fun_with_Words  阅读(116)  评论(0编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?









 和6张牌。

点击右上角即可分享
微信分享提示