整理了四十个好用到起飞的 Python 技巧!(3)

上一篇 / 下一篇  2022-01-17 10:32:27

  21 过滤器 filter() 函数
  过滤器filter()函数的工作顾名思义。它通过内部传递的特定函数来过滤特定的迭代器。并返回一个迭代器。
  语法
  filter(function, iterator)  
  mixed_number = [8, 15, 25, 30,34,67,90,5,12]  
  filterfiltered_value = filter(lambda x: x > 20, mixed_number)  
  print(f"Before filter: {mixed_number}")  
  print(f"After filter: {list(filtered_value)}") 
  输出
  Before filter:[8, 15, 25, 30, 34, 67, 90, 5, 12]
  After filter:[25, 30, 34, 67, 90]
  22 创建没有参数边界的函数
  你可以无需在意参数而创建一个函数。可以在调用函数时传递任意数量的参数。
  def multiplication(*arguments):  
      mul = 1  
      for i in arguments:  
          mulmul = mul * i  
      return mul  
  print(multiplication(3, 4, 5))  
  print(multiplication(5, 8, 10, 3))  
  print(multiplication(8, 6, 15, 20, 5)) 
  输出
  60 
  1200 
  72000
  23 一次迭代两个或多个列表
  你可以使用 enumerate 函数迭代单个列表,但是当你有两个或多个列表时,你也可以使用'zip()'函数迭代它们。
  capital = ['Vienna', 'Paris', 'Seoul',"Rome"]  
  countries = ['澳大利亚', '法国', '韩国',"意大利"]  
  for cap, country in zip(capital, countries):  
      print(f"{cap} 是 {country} 的首都") 
  输出
  Vienna 是 澳大利亚 的首都 
  Paris 是 法国 的首都 
  Seoul 是 韩国 的首都 
  Amsterdam 是 意大利 的首都
  24 改变句子中字母的大小写
  如果你想改变字母的大小写,即大写到小写,小写到大写,那么你可以使用一个叫做'swapcase'的函数实现这一功能。
  sentence = "Data STUDIO"  
  changed_sen = sentence.swapcase()  
  print(changed_sen) 
  输出
  dATA studio
  25 检查对象使用的内存大小
  要检查对象使用的内存,首先导入 'sys' 库,然后使用该库中名为 'getsizeof' 的方法。它将返回对象使用的内存大小。
  import sys 
  mul = 5*6  
  print(sys.getsizeof(mul)) 
  输出
  28
  26 Map() 函数
  'Map()' 函数用于特定的功能应用到一个给定的迭代器。
  语法
  map(function, iterator)
  values_list = [8, 10, 6, 50]  
  quotient = map(lambda x: x/2, values_list)  
  print(f"Before division: {values_list}")  
  print(f"After division: {list(quotient)}") 
  输出
  Before division:[8, 10, 6, 50] 
  After division:[4.0, 5.0, 3.0, 25.0]
  27 反转整个字符串
  要反转字符串,你可以使用切片方法。
  value = "OIDUTS ataD"  
  print("Reverse is:", value[::-1]) 
  输出
  Reverse is: Data STUDIO
  28 代码块的执行时间
  当你训练机器学习或深度学习模型,或者只是运行一个代码块时,获取需要检查运行代码块花费了多少时间。你可以选择在代码块的顶部使用一个魔法函数'%%time'。它将显示运行代码块所花费的时间。
  %%time  
  sentence = " Data STUDIO."  
  changed_sen = sentence.swapcase()  
  print(changed_sen)  
  输出
  dATA studio. 
  CPU times: user 145 μs, sys: 578 μs,
  total: 723 μs 
  Wall time: 1.04 ms
  29 删除字符串的左侧或右侧字符
  有两个函数称为 'rstrip()' 和 'lstrip()','rstrip()' 用于从字符串右侧删除某个字符,而 'lstrip()' 用于从字符串左侧删除某个字符。两个函数的默认值都是空格。但是你可以传递你的特定字符以将它们从字符串中删除。
  sentence1 = "Data STUDIO     "  
  print(f"After removing the right space: {sentence1.rstrip()}")   
  sentence2 = "        Data STUDIO"  
  print(f"After removing the left space: {sentence2.lstrip()}")  
  sentence3 = "Data STUDIO .,bbblllg"  
  print("After applying rstrip:", sentence3.rstrip(".,blg")) 
  输出
  After removing the right space: Data STUDIO    
  After removing the left space: Data STUDIO    
  After applying rstrip: Data STUDIO  
  你可以通过在其中运行 for 循环来计算元素在列表中出现的次数。但是你可以更轻松地做到这一点,只需调用名为'count'的列表中的方法即可。  
  cities= ["Amsterdam", "Berlin", "New York",   
           "Seoul", "Tokyo", "Paris", "Paris", 
           "Vienna","Paris"] 
  print("Paris appears", cities.count("Paris"), "times in the list") 
  输出
  Paris appears 3 times in the list
  30 在元组或列表中查找元素的索引
  只需在该元组或列表上调用一个名为'index'的简单方法,就可以在该元组或列表中找到元素的索引。
  cities_tuple = ("Berlin", "Paris", 5, "Vienna", 10)  
  print(cities_tuple.index("Paris"))   
  cities_list = ['Vienna', 'Paris', 'Seoul',"Amsterdam"]  
  print(cities_list.index("Amsterdam")) 
  输出
  1 
  3
  31 清空列表或集合中元素
  可以通过在列表或集合上应用称为'clear'的方法从列表或集合中删除所有元素。
  cities_list = ['Vienna', 'Paris', 'Seoul',"Amsterdam"]  
  print(f"Before removing from the list: {cities_list}")  
  cities_list.clear()  
  print(f"After removing from the list: {cities_list}")  
  cities_set = {'Vienna', 'Paris', 'Seoul',"Amsterdam"}  
  print(f"Before removing from the set: {cities_set}")  
  cities_set.clear() 
  print(f"After removing from the set: {cities_set}") 
  输出
  Before removing from the list: ['Vienna',
              'Paris', 'Seoul', 'Amsterdam'] 
  After removing from the list: [] 
  Before removing from the set: {'Seoul',
              'Amsterdam', 'Paris', 'Vienna'} 
  After removing from the set: set()
  32 连接两个集合
  要加入两个集合,你可以应用称为union()的方法。它将加入你应用该方法的两个列表。
  set1 = {'Vienna', 'Paris', 'Seoul'}  
  set2 = {"Tokyo", "Rome",'Amsterdam'}  
  print(set1.union(set2)) 
  输出
  {'Seoul', 'Rome', 'Paris',
  'Amsterdam', 'Tokyo', 'Vienna'}
  33 根据频率对列表的值排序
  首先,使用名为 collections 的模块中的'counter'来测量每个值的频率,然后对计数器的结果应用名为'most_common'的方法,根据频率对列表中的值进行排序。
  from collections import Counter  
  count = Counter([7, 6, 5, 6, 8, 6, 6, 6])  
  print(count)  
  print("根据频率对值进行排序:", count.most_common()) 
  输出:
  Counter({6: 5, 7: 1, 5: 1, 8: 1}) 
  根据频率对值进行排序:[(6, 5), (7, 1), (5, 1), (8, 1)]
  34 从列表中删除重复值
  首先将列表转换为集合,这将删除重复值,因为集合不包含重复值。然后再次将集合转换为列表,这样就可以轻松地从列表中删除重复的值。
  cities_list = ['Vienna', 'Paris', 'Seoul',  
                 "Amsterdam","Paris","Amsterdam", "Paris"]  
  cities_list = set(cities_list)  
  print("从列表中删除重复值后:", list(cities_list)) 
  输出
  从列表中删除重复值后:['Vienna', 'Amsterdam',
                   'Seoul', 'Paris']
  35 列表中元素连接为句子
  通过使用称为'join'的方法,可以连接列表的所有单个元素并生成单个字符串或句子。
  words_list = ["数据", "STUDIO", "云朵君"]  
  print(" ".join(words_list)) 
  输出
  数据STUDIO云朵君
  36 一次从函数返回多个值
  可以在 python 中做到一次从一个函数返回多个值。
  def calculation(number):  
      mul = number*2  
      div = number/2  
      summation = number+2  
      subtract = number-2  
      return mul, div, summation, subtract  
  mul, div, summation, subtract = calculation(10) 
   print("乘法:", mul) 
  print("除法:", div)  
  print("加法:", summation)  
  print("减法:", subtract) 
  输出
  乘法: 20 
  除法: 5.0 
  加法: 12 
  减法: 8
  37 找出两个列表之间的差异
  首先,将列表转换为集合,然后对这些集合应用称为'symmetric_difference'的方法。这将返回这两个列表之间的差异。
  cities_list1 = ['Vienna', 'Paris', 'Seoul',"Amsterdam", "Berlin", "London"]  
  cities_list2 = ['Vienna', 'Paris', 'Seoul',"Amsterdam"]  
  cities_set1 = set(cities_list1)  
  cities_set2 = set(cities_list2)  
  difference = list(cities_set1.symmetric_difference(cities_set2))  
  print(difference) 
  输出
  ['Berlin', 'London']
  38 将两个列表合并为一个字典
  首先,在这两个列表上应用 zip 函数,然后将 zip 函数的输出转换为字典。你的工作已完成,将两个列表转换为一个字典就是这么容易。
  number = [1, 2, 3]  
  cities = ['维也纳', '巴黎', '首尔']  
  result = dict(zip(number, cities))  
  print(result) 
  输出
  {1:'维也纳', 2:'巴黎', 3:'首尔'}
  39 执行字符串表示的代码
  将字符串编译成python能识别或可执行的代码,也可以将文字读成字符串再编译。
  s  = "print('helloworld')"  
  r = compile(s,"<string>", "exec")  
  exec(r) 
  输出
  helloworld
  40 字符串格式化
  格式化输出字符串,format(value, format_spec)实质上是调用了value的format(format_spec)方法。
  print("i am {0},age{1}".format("tom",18))  
  输出
  i am tom,age18

  2021软件测试行业前景分析,需要你的参与。点击下方链接填写调查问卷,只需3分钟,不仅能助力行业趋势,更有资料礼品赠送~
  链接:http://vote.51testing.com/

TAG: 软件开发 Python python

 

评分:0

我来说两句

Open Toolbar