For loops (novice)

前端 未结 5 774

I recently started learning Python, and the concept of for loops is still a little confusing for me. I understand that it generally follows the format for x in y

5条回答
  •  遥遥无期
    2021-01-18 03:43

    Bear in mind that the 'list' part of the Python can be any iterable sequence.

    Examples:

    A string:

    for c in 'abcdefg':
       # deal with the string on a character by character basis...
    

    A file:

    with open('somefile','r') as f:
        for line in f:
             # deal with the file line by line
    

    A dictionary:

    d={1:'one',2:'two',3:'three'}
    for key, value in d.items():
       # deal with the key:value pairs from a dict
    

    A slice of a list:

    l=range(100)
    for e in l[10:20:2]:
        # ever other element between 10 and 20 in l 
    

    etc etc etc etc

    So it really is a lot deeper than 'just some list'

    As others have stated, just set the iterable to be what you want it to be for your example questions:

     for e in (i*i for i in range(10)):
         # the squares of the sequence 0-9...
    
     l=[1,5,10,15]
     for i in (i*2 for i in l):
         # the list l as a sequence * 2...
    

提交回复
热议问题