zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    自定义Android Studio方法注释模板
    shell 大型脚本工具开发实战
    Shell 脚本操作数据库实战
    awk 常用选项及数组的用法和模拟生产环境数据统计
    awk 条件及循环语句和字符串函数
    awk 表达式
    awk 概述及常用方法总结
    sed 追加文件内容
    sed 修改文件内容
    sed 删除文本中的内容
  • 原文地址:https://www.cnblogs.com/bangbangjiang/p/3372639.html
Copyright © 2011-2022 走看看