Python loop structure (for-in)

Source: Internet
Author: User
Tags builtin

cyclic structure (for-in)
  • Description: Also a loop structure, often used to traverse strings, lists, tuples, dictionaries, etc.

  • Format:

    Y:
    Loop body

    Execution process: X in turn represents an element in Y, traversing through all elements loop end

  • Example 1: Traversing a string


    ' I love your more than I can say '
    S
    print (i)
  • Example 2: Traversing a list

     l = [ Goose Goose Goose,  "Song to Heaven", " Hoe wo Day copse ',  ' spring planting a grain of millet ' 
    ?
    for i in l:
       print (i)
    ?
    # can get the following table, enumerate each loop can get the following table and elements
    for i, v in enumerate (l):
       print (i, v)
  • Example 3: Traversing a dictionary


    D = {' A ':' Apple ',' B ':' Banana ',' C ':' Car ',' d ':' Desk '}
    ?
    ForKeyin d:
       # Traversing the dictionary is the key
       print (key, d.get (key))
    ?
    # for key, value in D.items ():
    # two ways equivalent D.items () <=> Dict.items (d)
    for key, value in dict. items (d):
        Print (key, value)
  • List-Generated

      • Iterate objects: Lists, tuples, dictionaries, and so on are iterative objects, which are objects that can be traversed

      • Range, use the following:


    Printrange (10))
    # You can build an iterative object that starts from 0 to 10 consecutive integers
    print (range ( 0, 10))
    ?
    # can traverse
    for i in range (10):
       print (i)
    ?
    # cast to list
    print (list ( range (1, 11)))
      • List generation: Quickly generate lists with specific rules


    # List-Generated
    Print ([IForIInchRange1,11)])
    Print ([I*2ForIInchRange1,11)])
    Print ([I*IFori in range (1 , 11)])
    print ([str (i) for i in range (1, 11)])
    print ([i for i in range (1 , 11) if i % Span class= "Cm-number" >2 = = 0])
  • Multiple loops: A nested loop in a loop

      • Example 1: Enter an integer from the terminal to print as a shape:


    n =intInput' Please enter an integer: ')
    ?
    ‘‘‘
    1
    0 S
    1 2 3
    1 2 3 4
    ...
    1 2 3 4 ... n
    ‘‘‘
    ?
    ‘‘‘
    j = 1
    While J <= N:
    i = 1
    While I <= J:
    Print (I, end= ")
    i + = 1
    Print ()
      J + = 1
    "
    ?
    for i in range (1, n +1):
       for j in range (1, i+1):
            Print (j, end= ")
       print ()
      • Example 2: Print a 99 multiplication table


    Fori in range (1 , 10):
       for j Span class= "Cm-keyword" >in range (1, i< Span class= "Cm-operator" >+1):
            print ( ' {}x{}={} '. Format (j, i, j *i), end= ')
       print ()
      • Example 3: List sorting (selection method)


    L = [1,9,4,2,0,8,3,7]
    ?
    # Get length
    n =LenL
    ?
    # The outer loop is used to control the number of loops in the loop, and each circle can determine the position of an element
    # Make sure n elements start with only a n-1 circle
    ForIInchRangeN-1):
    # The Inner loop is used to compare the size of the interchange element, a circle to determine an element
    ForJInchRangeI+1, n):
            # if not appropriate
           if l[i" > l[j]:
               # Exchange two variables
               l[i], l[j] = l[j], l[i]
    ?
    print (l)
    • Practice:

      1. Sort a list by using bubbling


        1. Bubble: Each time comparing the adjacent two elements, not suitable for exchange, and then backward, a circle down can be determined an element
        2. Need to use a double loop, the outer loop control loop number of loops, the inner layer control how to exchange a circle
      2. Traverse List, Print: My name is XXX, this year yyy year old, I come from zzz, the data are as follows

        lt = [


        {' name ': ' Xiao Wang ', ' age ': ' Info ': [(' Phone ', ' 123 '), (' Dizhi ', ' Guangzhou ')},
        {' name ': ' Small Fang ', ' age ': +, ' info ': [(' Phone ', ' 789 '), (' Dizhi ', ' Shenzhen ')},
        {' name ': ' Du ', ' age ': ' Info ': [(' Phone ', ' 567 '), (' Dizhi ', ' Beijing ')},
        {' name ': ' Little Meng ', ' age ':--' info ': [(' Phone ', ' ' "') ' (' Dizhi ', ' Shanghai ')},
        {' name ': ' Little Joe ', ' age ': +, ' info ': [(' Phone ', ' 111 '), (' Dizhi ', ' Henan ')},
        ]
      3. Enter two integers from the terminal m,n, print the M*n table, such as: 2, 5, print the following effect


        1 2 3) 4 5
        6 7 8) 9 10

Python loop structure (for-in)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.