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
  • 相关阅读:
    Flink 状态生命周期
    jpa使用@CollectionTable创建表
    Java的四种引用---强软弱虚
    ThreadLocal与内存泄露
    Flink 1.11 Table API 实现kafka到mysql
    FLIink 1.11 SQL 构建一个端到端的流式应用
    Flink1.11编译
    Flink运行yarn-session报错 java.lang.NoClassDefFoundError: org/apache/hadoop/yarn/exceptions/YarnException
    欢迎订阅AI科技导读微信公众号,获取人工智能的最新技术解读教程!
    深度学习深刻理解和应用--人工智能从业人员必看知识
  • 原文地址:https://www.cnblogs.com/bangbangjiang/p/3372639.html
Copyright © 2011-2022 走看看