51Testing软件测试论坛

 找回密码
 (注-册)加入51Testing

QQ登录

只需一步,快速开始

微信登录,快人一步

查看: 573|回复: 0
打印 上一主题 下一主题

[转贴] 12 个用于日常编程的杀手级 Python 代码片段

[复制链接]
  • TA的每日心情
    无聊
    前天 09:06
  • 签到天数: 941 天

    连续签到: 3 天

    [LV.10]测试总司令

    跳转到指定楼层
    1#
    发表于 2022-8-2 09:30:33 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
    1、正则表达式
      正则表达式是 Python 中匹配模式、搜索和替换字符串、验证字符串等的最佳技术。现在,您无需为此类工作使用循环和列表。
      查看以下关于验证电子邮件格式的正则表达式片段代码示例:
    1. # Regular Expression Check Mail
    2.   import re
    3.   def Check_Mail(email):
    4.      pattern = re.compile(r'([A-Za-z0-9]+[.-_])*[A-Za-z0-9]+@[A-Za-z0-9-]+(\.[A-Z|a-z]{2,})+')
    5.      if re.fullmatch(pattern, email):
    6.          print("valid")
    7.      else:
    8.          print("Invalid")
    9.   Check_Mail("codedev101@gmail.com") #valid
    10.   Check_Mail("codedev101-haider@uni.edu")  #Invalid
    11.   Check_Mail("code-101-work@my.net") # Invalid
    复制代码
    2、Pro Slicing
      这个简单的代码片段将帮助您像专业人士一样对列表进行切片。查看下面的示例代码:
    1. # Pro Slicing
    2.   # list[start:end:step]
    3.   mylist = [1, 2, 3, 5, 5, 6, 7, 8, 9, 12]
    4.   mail ="codedev-medium@example.com"
    5.   print(mylist[4:-3]) # 5 6 7
    6.   print(mail[8 : 14]) # medium
    复制代码
    3、Swap without Temp
      您是否使用 Temp 变量来交换两个数据,而不是在 Python 中您不需要使用它?在此代码段中,我将与您分享如何在不使用 temp 的情况下交换两个数据变量。
      查看下面的代码:
    1.  # Swap without Temp
    2.   i = 134
    3.   j = 431
    4.   [i, j] = [j, i]
    5.   print(i) #431
    6.   print(j) #134
    复制代码
    4、Magic of F-string
      我们可能使用 format() 方法或“%”方法来格式化字符串中的变量。这段代码将向您介绍 F 字符串,它比另一种格式要好得多。
      看看下面的示例代码:
    1.  # Magic of f-String
    2.   # Normal Method
    3.   name = "Codedev"
    4.   lang = "Python"
    5.   data = "{} is writing article on {}".format(name, lang)
    6.   print(data)
    7.   # Pro Method with f-string
    8.   data = f"{name} is writing article on {lang}"
    9.   print(data
    复制代码
    5、获取索引
      现在您不再需要 Loop 来查找特定元素的索引。您可以使用列表中的 index() 方法来完成。
      查看下面的代码:
    1. # Get Index
    2.   x = [10 ,20, 30, 40, 50]
    3.   print(x.index(10)) # 0  
    4.   print(x.index(30)) # 4
    5.   print(x.index(50)) # 2
    复制代码
    6、基于Another List的排序列表
      此代码段将向您展示如何根据另一个列表对列表进行排序。当您需要根据所需的位置进行排序时,此代码段非常方便。
    1. # Sort List based on another List
    2.   list1 =  ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"]
    3.   list2 = [ 0, 1, 1, 1, 2, 2, 0, 1, 1, 3, 4]
    4.   C = [x for _, x in sorted(zip(list2, list1), key=lambda pair: pair[0])]
    5.   print(C) # ['a', 'g', 'b', 'c', 'd', 'h', 'i', 'e', 'f', 'j', 'k']
    复制代码
    7、 反转字典
      现在您不需要循环来反转任何字典。此代码段代码将在第二次尝试该代码段代码时反转字典。
    1. # Invert the Dictionary
    2.   def Invert_Dictionary(data):
    3.      return  {value: key for key, value in data.items()}
    4.   data = {"A": 1, "B":2, "C": 3}
    5.   invert = Invert_Dictionary(data)
    6.   print(invert) # {1: 'A', 2: 'B', 3: 'C'}
    复制代码
    8、多线程
      多线程将帮助您同时并行运行 Python 函数。假设您想同时执行 5 个函数,而无需等待每个函数完成。
      查看下面的代码段:
    1.  # Multi-threading
    2.   import threading
    3.   def func(num):
    4.      for x in range(num):
    5.          print(x)
    6.   if __name__ == "__main__":
    7.      t1 = threading.Thread(target=func, args=(10,))
    8.      t2 = threading.Thread(target=func, args=(20,))
    9.      t1.start()
    10.      t2.start()
    11.      t1.join()
    12.      t2.join()
    复制代码
    9、列表中出现最多的元素
      此片段代码将简单地计算列表中出现次数最多的元素。我已经展示了两种方法来做到这一点。
      在下面查看它:
    1.  # Element Occur most in List
    2.   from collections import Counter
    3.   mylst = ["a", "a", "b", "c", "a", "b","b", "c", "d", "a"]
    4.   # Method 1
    5.   def occur_most1(mylst):
    6.      return max(set(mylst), key=mylst.count)
    7.   print(occur_most1(mylst)) # a
    8.   # Method 2  
    9.   # Much Faster then Method 1
    10.   def occur_most2(mylst):
    11.      data = Counter(mylst)
    12.      return data.most_common(1)[0][0]
    13.   print(occur_most2(mylst)) # a
    复制代码
    10、分割线
      有一个逐行格式的原始文本,并希望将其分成几行。此代码段将在一秒钟内解决您的问题。
    1. # Split lines
    2.   data1 = """Hello to
    3.   Python"""
    4.   data2 = """Programming
    5.   Langauges"""
    6.   print(data1.split("\n")) # ['Hello to', 'Python']
    7.   print(data2.split("\n")) # ['Programming', ' Langauges']
    复制代码
    11、 将列表映射到字典
      此代码段将帮助您将任意两个列表转换为字典格式。要了解它是如何工作的,请查看下面的代码:
    1. # Map List into Dictionary
    2.   def Convert_to_Dict(k, v):
    3.      return dict(zip(k, v))
    4.   k = ["a", "b", "c", "d", "e"]   
    5.   v = [1, 2, 3, 4, 5]
    6.   print(Convert_to_Dict(k, v)) # {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
    复制代码
    12、解析电子表格
      现在您不需要 Pandas 或任何其他外部 Python 包来解析电子表格。Python 有一个内置的 CSV 模块,这段代码将向您展示如何使用它。
    1. # Parse Spreadsheet
    2.   import csv
    3.   #Reading
    4.   with open("test.csv", "r") as file:
    5.      csv_reader = csv.reader(file)
    6.      for row in csv_reader:
    7.          print(row)
    8.   file.close()
    9.   #Writing
    10.   header = ["ID", "Languages"]
    11.   csv_data = [234, "Python", 344, "JavaScript", 567, "Dart"]
    12.   with open("test2.csv", 'w', newline="") as file:
    13.      csv_writer = csv.writer(file)
    14.      csv_writer.writerow(header)
    15.      csv_writer.writerows(csv_data)
    复制代码














    分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
    收藏收藏
    回复

    使用道具 举报

    本版积分规则

    关闭

    站长推荐上一条 /1 下一条

    小黑屋|手机版|Archiver|51Testing软件测试网 ( 沪ICP备05003035号 关于我们

    GMT+8, 2024-5-2 06:25 , Processed in 0.067596 second(s), 23 queries .

    Powered by Discuz! X3.2

    © 2001-2024 Comsenz Inc.

    快速回复 返回顶部 返回列表