• 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
  • 相关阅读:
    BGP deterministic-med & compare-med
    BGP Always-compare-med & Deterministic-med
    BGP实验 MED , Cyrus
    BGP Lab AS-path prepend last-as
    详解C/C++中volatile关键字
    38、hashtable中解决冲突有哪些方法?
    37、STL中unordered_map和map的区别和应用场景
    36、set和map的区别,multimap和multiset的区别
    35、STL中map的实现
    34、STL中set的实现?
  • 原文地址:https://www.cnblogs.com/bangbangjiang/p/3372639.html
Copyright © 2020-2023  润新知