• python学习笔记--for循环


    推荐一个学习语言的网站:http://www.codecademy.com

    有教程,可以边学边写,蛮不错的。

    for循环:

    1.for loops allow us to iterate through all of the elements in a list from the left-most (or zeroth element) to the right-most element. A sample loop would be structured as following:

    使用for循环可以遍历一个列表,从最左到最右:

    a = ["List of some sort”]
    for x in a: 
        # Do something for every x
    

    2.You can also use a for loop on a dictionary to loop through its keys with the following:可以使用for循环通过key值去遍历一个字典

    webster = {
        "Aardvark" : "A star of a popular children's cartoon show.",
        "Baa" : "The sound a goat makes.",
        "Carpet": "Goes on the floor.",
        "Dab": "A small amount."
    }
    
    # Add your code below!
    for key in webster:
        print webster[key]

    Note that dictionaries are unordered, meaning that any time you loop through a dictionary, you will go through every key, but you are not guaranteed to get them in any particular order.遍历过程是无序的

    3.While looping, you may want to perform different actions depending on the particular item in the list. This can be achieved by combining your loops with control flow (if/else statements) that might resemble the following:

    Make sure to keep track of your indentation or you may get confused!可以使用if/else语句去控制for的内容

    a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
    
    for number in a:
        if number % 2 == 0:
            print number

    4.Functions can also take lists as inputs and perform various operations on those lists.

    x = ['fizz','buzz','fizz']
    
    def fizz_count(x):
        count = 0
        for word in x:
            if word == 'fizz':
                count = count + 1
        return count      

    5.String Looping:As we've mentioned, strings are like lists with characters as elements. You can loop through strings the same way you loop through lists!字符遍历

    for letter in "Codecademy":
        print letter
        
    # Empty lines to make the output pretty
    print
    print
    
    word = "Programming is fun!"
    
    for letter in word:
        # Only print out the letter i
        if letter == "i":
            print letter
  • 相关阅读:
    大数据基础---安装ClouderaManager,CDH和Impala,Hue,oozie等服务
    大数据基础---ClouderaManager和CDH是什么?
    大数据基础---通过Flume、Sqoop分析日志
    VS2015设置快捷键
    QGIS添加在线地图
    Python + SQLite + ST_Geometry
    Python 安装 selenium 与 chromedriver.exe
    Python IDLE 编译器 显示代码行号
    Python IDLE 编辑器开启代码自动提示
    Python IDLE编辑器打开后缀名为.py的文件
  • 原文地址:https://www.cnblogs.com/bangbangjiang/p/3372639.html
Copyright © 2020-2023  润新知