51Testing软件测试论坛

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

QQ登录

只需一步,快速开始

微信登录,快人一步

手机号码,快捷登录

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

[转贴] 快速掌握Python中的循环技术

[复制链接]
  • TA的每日心情
    擦汗
    14 小时前
  • 签到天数: 1021 天

    连续签到: 2 天

    [LV.10]测试总司令

    跳转到指定楼层
    1#
    发表于 2021-3-11 09:46:01 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
     1. 使用enumerate()循环整个序列  当循环遍历一个序列(如列表、元组、范围对象、字符串)时,可以使用enumerate()函数同时检索位置索引和相应的值。
      (1) 使用enumerate()遍历列表:
      示例1:
      使用enumerate()函数遍历列表,返回一个包含可迭代对象中的计数和值的元组。一般情况下,计数从0开始。
      colors=['red','green','blue']
      for color in enumerate(colors):
          print (color)
      #Output:
      (0, 'red')
      (1, 'green')
      (2, 'blue')

      示例2:
      count从5开始循环迭代器。
      colors=['red','green','blue']
      for color in enumerate(colors,5):
          print (color)
      '''
      Output:
      (5, 'red')
      (6, 'green')
      (7, 'blue')
      '''

      (2) 使用enumerate()循环字符串:
      示例:
      使用enumerate()函数遍历字符串将返回一个包含可迭代对象的计数和值的元组。一般情况下,计数从0开始。
      s='python'
      for i in enumerate(s):
          print (i)
      '''     
      #Output:
      (0, 'p')
      (1, 'y')
      (2, 't')
      (3, 'h')
      (4, 'o')
      (5, 'n')
      '''

      2. 使用zip()函数循环两个或多个序列
      要同时循环两个或多个序列,可以使用zip()函数对条目进行配对。
      (1) 使用zip()循环两个相同长度的序列
      示例:
      num = [1, 2, 3]
      colors= ['red', 'blue', 'green']
      for i in zip(num, colors):
          print(i)

      '''
      Output:
      (1, 'red')
      (2, 'blue')
      (3, 'green')
      ''

      (2) 使用zip()循环两个不同长度的序列
      如果使用zip()遍历两个长度不同的序列意味着当最短的可迭代对象耗尽时停止。
      示例:
      colors=['red','green','blue']
      num=[1,2,3,4,5,6,7,8,9,10]
      for i in zip(colors,num):
          print (i)
      '''
      Output:
      ('red', 1)
      ('green', 2)
      ('blue', 3)
      '''

      (3) 使用zip()循环两个或多个序列:
      示例:
      colors=['red','apple','three']
      num=[1,2,3]
      alp=['a','b','c']
      for i in zip(colors,num,alp):
          print (i)
      '''
      Output:
      ('red', 1, 'a')
      ('apple', 2, 'b')
      ('three', 3, 'c')
      '''

      3. itertools.zip_longest ()
      创建一个从每个可迭代对象中聚合元素的迭代器。如果可迭代对象的长度不均匀,则用fillvalue填充缺失的值。迭代继续,直到最长的可迭代对象耗尽。
      使用itertools.zip_longest()循环两个不同长度的序列。
      示例1:如果不指定fillvalue,则默认为None。
      from itertools import zip_longest
      colors=['red','apple','three']
      num=[1,2,3,4,5]
      for i in zip_longest(colors,num):
          print (i)
      '''
      Output:
      ('red', 1)
      ('apple', 2)
      ('three', 3)
      (None, 4)
      (None, 5)
      '''

      示例2:指定fillvalue。
      from itertools import zip_longest
      colors=['red','apple','three']
      num=[1,2,3,4,5]
      for i in zip_longest(colors,num,fillvalue='z'):
          print (i)
      '''
      Output:
      ('red', 1)
      ('apple', 2)
      ('three', 3)
      ('z', 4)
      ('z', 5)
      '''

      4. 使用sorted()函数按已排序的顺序循环序列
      sorted():从iterable中的项返回一个新的排序列表。
      示例:1使用sorted()函数按排序(升序)遍历序列(list)。
      num=[10,5,20,25,30,40,35]
      for i in sorted(num):
          print (i)
      '''
      Output:
      5
      10
      20
      25
      30
      35
      40
      '''

      示例2:使用sorted()函数按排序(降序)遍历序列(list)。
      num=[10,5,20,25,30,40,35]
      for i in sorted(num,reverse=True):
          print (i)
      '''
      Output:
      40
      35
      30
      25
      20
      10
      5
      '''

      示例3:使用sorted()函数按排序(升序)遍历字典。默认情况下,它将对字典中的键进行排序。
      d={'f':1,'b':4,'a':3,'e':9,'c':2}
      for i in sorted(d.items()):
          print (i)
      #Output:
      ('a', 3)
      ('b', 4)
      ('c', 2)
      ('e', 9)
      ('f', 1)

      示例4:使用已排序的函数按已排序的顺序循环字典。在已排序的函数中使用key参数,根据字典的值对其排序。
      d={'f':1,'b':4,'a':3,'e':9,'c':2}
      #sorting by values in the dictionary
      for i in sorted(d.items(),key=lambda item:item[1]):
          print (i)

      #Output:
      ('f', 1)
      ('c', 2)
      ('a', 3)
      ('b', 4)
      ('e', 9)

      5. 使用reversed()函数遍历序列
      reversed(seq):

      返回反向迭代器。seq必须是一个具有__reversed__()方法或支持序列协议(__len__()方法和__getitem__()方法,参数从0开始)的对象。
      示例:
      反向循环一个序列,然后调用reversed()函数。
      colors=['red','green','blue','yellow']
      for i in reversed(colors):
          print (i)
      '''
      Output:
      yellow
      blue
      green
      red
      '''

      6. 循环查找字典
      当循环遍历字典时,可以使用items()方法同时检索键和相应的值。
      示例:
      d={'a':1,'b':2,'c':3}
      for k,v in d.items():
          print (k,v)
      #Output:
      a 1
      b 2
      c 3

      7. 在迭代时修改集合
      在遍历同一个集合时修改集合的代码可能很难正确处理。相反,循环遍历集合的副本或创建一个新集合通常更简单。
      策略1:对副本进行迭代
      如果希望在迭代时删除字典中的项,则在字典的副本上进行迭代:
      d={'a':1,'b':2,'c':3}
      for k,v in d.copy().items():
          if v%2==0:
              del d[k]
      print (d)
      #Output:{'a': 1, 'c': 3}

      策略2:创建一个新的集合
      d={'a':1,'b':2,'c':3}
      d1={}
      for k,v in d.items():
          if v%2!=0:
              d1[k]=v
      print (d1)
      #Output:{'a': 1, 'c': 3}
      print (d)
      #Output:{'a': 1, 'b': 2, 'c': 3}


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

    使用道具 举报

    本版积分规则

    关闭

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

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

    GMT+8, 2024-9-19 23:16 , Processed in 0.070535 second(s), 24 queries .

    Powered by Discuz! X3.2

    © 2001-2024 Comsenz Inc.

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