python学习之旅---编码技巧

    技术2025-01-19  15

    目录

    0、命名方式1、变量的交换(Swapping Variables)2、字符串格式化(String Formatting)3、Yield语法(Yield Statement)4、列表解析式(List Comprehension)5、Enumerate函数(Enumerate Function)6、反向遍历(Looping Backwards)7、字典的合并操作(Dictionary Merging)8、三元运算符(Ternary Operator)9、序列解包(Sequence Unpacking)10、With语句(With Statement)

    0、命名方式

    定义函数的命名:

    # 1、 --- 推荐使用这种 def getNovelListUrl(): 2def getnovelnisturl(): # 3、 def get_Novel_List_Url(): # 4、 def get_novel_nist_url():

    1、变量的交换(Swapping Variables)

    a = 1 b = 2 # 传统的变量交换代码: temp = a a = b b = temp # 编程技巧: a,b = b,a

    2、字符串格式化(String Formatting)

    name = "Liming" # 通常情况下,我们利用加号来进行字符串的连接: print("Hi, I'm " + name)

    name = "Liming" country = "China" age = 23 # 但是如果一句话比较长,则显得非常杂乱并且不易阅读 print("Hi, I'm " + name + ". I'm from " + country + ". And I'm " + str(age) + ".") # 改进方式1: print("Hi, I'm %s. I'm from %s. And I'm %d." %(name,country,age)) # 改进方法2: print("Hi, I'm {}. I'm from {}. And I'm {}.".format(name,country,age)) # 推荐写法(python3.6以上版本): print(f"Hi, I'm {name}. I'm from {country}. And I'm {age}.")

    3、Yield语法(Yield Statement)

    # 原定义方式: def fibonacci(n): a = 0 b = 1 nums = [] for _ in range(n): nums.append(a) a,b = b,a + b return nums

    # Yield定义方式: # 使用yield的好处:我们并不需要等列表生成结束之后再一个一个的输出 def fibonacci(n): a = 0 b = 1 for _ in range(n): yield a # 这里的yield表示:每当我们计算出一个元素,就立马将这个元素给送出去 a,b = b,a + b for i in fibonacci(10): print(i)

    4、列表解析式(List Comprehension)

    fruit = ["apple","pear","pineapple","orange","banana"] # 操作:将列表的每一项的改成大写 # 常规操作: for i in range(len(fruit)): fruit[i] = fruit[i].upper() # 改进方法: # fruit = [x.upper() for x in fruit] # 查看更改结果 print(fruit)

    fruit = ["apple","pear","pineapple","orange","banana"] # 操作:筛选或者过滤列表中的元素,比如:挑选出列表中以p开头的水果 filtered_fruit = [] for f in fruit: if f.startswith("p"): filtered_fruit.append(f) # 改进方法: # filtered_fruit = [x for x in fruit if x.startswith("p")] # 查看筛选结果 print(filtered_fruit)

    5、Enumerate函数(Enumerate Function)

    fruit = ["apple","pear","pineapple","orange","banana"] # 操作:按顺序输出某一个列表中的所有元素 # 常规操作: for x in fruit: print(x) # 同时得到列表元素的索引值和内容: for i,x in enumerate(fruit): print(i,x)

    6、反向遍历(Looping Backwards)

    fruit = ["apple","pear","pineapple","orange","banana"] # 反向遍历:按反序输出某一个列表中的所有元素 for i,x in enumerate(reversed(fruit)): print(i,x) # 按顺序遍历(Looping in Sorted Order) # 按照列表字母从a到z的排序方式 for i,x in enumerate(sorted(fruit)): print(i,x)

    7、字典的合并操作(Dictionary Merging)

    a = {"ross": "123456", "xiaoming": "abc123"} b = {"liler": "111111", "zhangsan": "12345678"} # 操作:将两个字典合并为一个字典 c = {} for k in a: c[k] = a[k] for k in b: c[k] = b[k] # 改进方法: # ** 在python中叫做解包unpacking d = {**a, **b} # 验证结果: print(c) print(d)

    8、三元运算符(Ternary Operator)

    # 根据数值大小的不同来进行选择 score = 50 if score > 60: s = "pass" else: s = "fail" # 改进方法: # s = "pass" if score > 60 else "fail" # 验证结果 print(s)

    9、序列解包(Sequence Unpacking)

    name = "San Zhang" # 操作:想提取出姓和名 str_list = name.split() # split() 把字符串按空格分割成多个字符串 first_name = str_list[0] last_name = str_list[1] # 改进方法: # first_name, last_name = name.split() # 验证结果 print(first_name,"-------",last_name)

    10、With语句(With Statement)

    # 常规操作: f = open("somefile.txt","r") s = f.read() f.close() # 改进方法: # with语句可以自动的帮我们关闭打开的文件 with open("somefile.txt","r") as f: s = f.read()
    Processed: 0.009, SQL: 9