zoukankan      html  css  js  c++  java
  • for循环、in、not in

    for循环可以遍历集合中任意一个元素

    1 a = ["hello", "world", "dlrb"]
    2 for b in a:
    3     print(b)

    我们定义了一个集合a,通过for循环指定变量b遍历集合a,最后print变量b输出集合中的所有元素

    输出结果:

    hello
    world
    dlrb

    或者使用for循环输出字符串中的每个元素:

    1 a = "dlrb"
    2 for b in a:
    3     print(b)

    输出结果:

    d
    l
    r
    b

    我们还可以通过几种方法查找某个元素是否在集合中:

    1 a = ["hello", "world", "dlrb"]
    2 b = "dlrb"
    3 if b in a:     
    4     print("yes")
    5 else:
    6     print("no")

    我们定义了一个集合a,定义了一个变量b,我们查找变量b所代表的字符串是否在集合a内,输出结果:

    yes

    not in的就是元素不在里面,用法都是一样的

    1 a = ["hello", "world", "dlrb"]
    2 b = "dlrb" in a
    3 print(b)

    我们定义了一个集合a,定义了一个变量b是一个判定语句:“dlrb”在集合a里面,根据结果会返回True或者False,输出结果:

    True

     for循环中break、continue同样适用

    1 a = "hello"
    2 for i in a:
    3     if i == "e":
    4         continue
    5     print(i)

    输出结果:

    h
    l
    l
    o

    我们输出除e之外的所有字符

    a = "hello"
    for i in a:
        if i == "e":
            break
        print(i)

    输出结果:

    h

    我们输出每个字符但遇到e便停止循环

    同样for循环中可以插入if、esle语句

    1 a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    2 for b in a:
    3     if b%2 == 0:
    4         print(b)
    5     else:
    6         pass

    我们定义了一个集合a:里面是整数,我们想要输出集合a中的所有偶数,输出结果:

    2
    4
    6
    8
    10
  • 相关阅读:
    C#计算两个时间年份月份天数(根据生日计算年龄)差,求时间间隔
    C#四舍五入保留一位小数
    给Editplus去掉.bak文件
    $().each() 与 $.each()解析
    VS 2013+Qt 5.4.1
    HDU 5228 ZCC loves straight flush( BestCoder Round #41)
    产品经理的修炼:如何把梳子卖给和尚
    c++ STL unique , unique_copy函数
    linux定时备份mysql数据库文件
    Python——异常基础
  • 原文地址:https://www.cnblogs.com/zhangzengqiang/p/7486676.html
Copyright © 2011-2022 走看看