python中for循环的用法_浅谈Python的for循环

6644a2e4e3b9b60b04ce190fa766c0a2.png

for循环在python中的重要性毋庸置疑,可是,我们真的把所有for循环的知识点都理解透了么?试试看以下内容:

  1. for 循环的基本格式
for 

iterable是可迭代对象,包括字符串,列表,元组,字典,集合,迭代器,列表生成式,生成器。itervar是可迭代对象每次调用__next__方法返回的一个元素。else子句是可选。

2. 迭代字符串

    output_list = []
    # 迭代字符串 - 最简单最常用版本
    this_str = 'it is a string'
    for char in this_str:
        output_list.append(char)
    print(output_list)      #out:['i', 't', ' ', 'i', 's', ' ', 'a', ' ', 's', 't', 'r', 'i', 'n', 'g']

    #使用分片和下标迭代字符串
    output_list.clear()
    for index in range(len(this_str)):
        char = this_str[index:index+1:1]
        output_list.append(char)
    print(output_list)      #out:['i', 't', ' ', 'i', 's', ' ', 'a', ' ', 's', 't', 'r', 'i', 'n', 'g']

    #改进版本,采用enumerate函数,生成下标
    output_list.clear()
    for index, char in enumerate(this_str):
        output_list.append(this_str[index])     #等效:output_list.append(char)
    print(output_list)

3. 迭代列表

    # 迭代列表
    output_list = []
    this_list = ['a', 'b', 'c', 1, 2, 3]
    for el in this_list:
        output_list.append(el)
    print(output_list)      #out:['a', 'b', 'c', 1, 2, 3]

4. 迭代元组

    # 迭代字元组
    output_list = []
    this_tuple = ('a', 'b', 'c', 1, 2, 3)
    for el in this_tuple:
        output_list.append(el)
    print(output_list)      #out:['a', 'b', 'c', 1, 2, 3]

5. 迭代字典

    # 迭代字典。使用items方法返回key和value
    this_dict = {0: 'a', 1: 'b', 2: 'c', 3: '1', 4: '2', 5: '3'}
    for key, value in this_dict.items():
        print('%s:%s' % (key, value))

    #获取key 使用keys方法获取key
    for key in this_dict.keys():
        print('key is:%s' % key)

    #获取value 使用values方法获取value
    for value in this_dict.values():
        print('value is:%s' % value)

6. 迭代集合

    # 迭代集合
    output_list = []
    this_set = {'a', 'b', 'c', 1, 2, 3}
    for el in this_set:
        output_list.append(el)
    print(output_list)      #out:[1, 2, 3, 'b', 'c', 'a']

7. 迭代列表生成式,通常用于从一个列表推导出另外一个列表(筛选,操作)

    # 迭代列表生成式 从一个列表推导到另外一个列表,所有元素都*2
    this_list = ['a', 'b', 'c', 1, 2, 3]
    output_list = []
    for el in [x * 2 for x in this_list]:
        output_list.append(el)
    print(output_list)      #out:'aa', 'bb', 'cc', 2, 4, 6]

    # 迭代列表生成式 从一个列表筛选到另外一个列表,只要是字符串的元素
    output_list.clear()
    for el in [x for x in this_list if type(x) is str]:
        output_list.append(el)
    print(output_list)      #out:['a', 'b', 'c']

8. 迭代生成器

    # 迭代生成器 方法一 使用类似列表生成器的方式
    output_list = []
    for el in (num * 2 for num in range(10)):
        output_list.append(el)
    print(output_list)      #out:[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

    # 迭代生成器 方法二 自定义一个函数并且用yield返回
    def get_number(max_num: int):
        for num in range(max_num):
            yield num * 2

    output_list = []
    for el in get_number(10):
        output_list.append(el)
    print(output_list)  # out:[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

9. 如何在迭代过程中移除元素(列表和字典)

我们先看看python手册是怎么说在迭代中移除元素的:

ba114e4cf13bd96f8847e65c923e4859.png
由于迭代中有计数器,不能直接删除元素

我们试试看:

    this_list = ['a', 'b', 'c', 1, 2, 3]
    #迭代中删除列表元素 和期待的输出结果不同!!
    for el in this_list:
        if type(el) is str:
            this_list.remove(el) #out: ['b', 1, 2, 3]

在迭代列表的过程中,移除所有的字符串类型的元素,期望的输出结果是[1,2,3],为什么是 ['b', 1, 2, 3]?因为,移除了元素以后,就破坏了计数器,在列表中也是通过计数器来索引的。所以我们可以这么做:

    this_list = ['a', 'b', 'c', 1, 2, 3]
    #使用副本来进行迭代,用原本来进行删除
    for el in this_list[:]:         #this_list[:]是用切片生成this_list的一个副本
        if type(el) is str:
            this_list.remove(el)    #out: [1, 2, 3]

再试试字典:

    this_dict = {0: 'a', 1: 'b', 2: 'c', 3: '1', 4: '2', 5: '3', 6: 1, 7: 2}
    for key, value in this_dict.items():
         if type(value) is str:
             del(this_dict[key])     #RuntimeError: dictionary changed size during iteration

可以这样写,遍历字典的key列表,同时根据key来删除元素

    this_dict = {0: 'a', 1: 'b', 2: 'c', 3: '1', 4: '2', 5: '3', 6: 1, 7: 2}
    for key in list(this_dict.keys()):
        if type(this_dict[key]) is str:
            del(this_dict[key])     #output: {6: 1, 7: 2}

希望这文章能帮到你。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值