python判断とループ

5420 ワード

じょうけんけってい
一般書式
if :           # if test    
         # Associated block
elif :         # Optional elifs    
    
else:                 # Optional else    
    

if/else三元式
    A = Y if X else Z

#    
>>> if choice == 'spam':
...     print(1.25)
... elif choice == 'ham':
...     print(1.99)
... elif choice == 'eggs':
...     print(0.99)
... elif choice == 'bacon':
...     print(1.10)
... else:
...     print('Bad choice')

#     
>>> A = 't' if '' else 'f'
>>> A
'f'


ループ
while一般フォーマット
while :           # Loop test    
           # Loop body
else:                   # Optional else   
           # Run if didn't exit loop with break
  • breakは、最近存在するループから飛び出します(ループ文全体をスキップします).
  • continueは、最近のループの先頭にジャンプします(ループの最初の行に来ます).
  • passは何もしないで、ただ空占位文です.バージョン違いのヒント:Python 3.0(Python 2.6ではなく)式を使用できる場所で使用できます...(3つの連続するポイント番号)でコードを省略します.
  • ループelseブロックは、ループが正常に離れたときにのみ実行される(すなわちbreak文に遭遇しない).

  • while一般フォーマット
    while :   
           
        if : break     # Exit loop now, skip else   
        if : continue  # Go to top of loop now, to test1
    else:   
                 # Run if we didn't hit a 'break'
    

    while例
    while x:                   # Exit when x empty    
        if match(x[0]):        
            print('Ni')        
            break              # Exit, go around else    
        x = x[1:]
    else:    
        print('Not found')     # Only here if exhausted x
    

    for一般フォーマット
    for  in :      # Assign object items to target    
            
        if : break           # Exit loop now, skip else    
        if : continue        # Go to top of loop now
    else:    
                       # If we didn't hit a 'break'
    

    for例
    #  
    >>> for x in ["spam", "eggs", "ham"]:
    ...     print(x, end=' ')
    ...spam eggs ham
    
    #   
    S = "lumberjack"
    >>> for x in S: print(x, end=' ')   # Iterate over a string...l u m b e r j a c k
    
    #  
    >>> T = [(1, 2), (3, 4), (5, 6)]
    >>> for (a, b) in T:                   # Tuple assignment at work
    ...     print(a, b)
    ...1 2
       3 4
       5 6
    
    #  
    >>> D = {'a': 1, 'b': 2, 'c': 3}
    >>> for key in D:
    ...    print(key, '=>', D[key])          # Use dict keys iterator and index
    ...a => 1
       c => 3
       b => 2
    
    #items      ( ,  )     ,           。
    >>> for (key, value) in D.items():
    ...    print(key, '=>', value)            # Iterate over both keys and values
    ...a => 1
       c => 3
       b => 2
       
    #       
    >>> S = 'abcdefghijk'
    >>> for c in S[::2]: 
        print(c, end=' ')
    ...a c e g i k
    
    # python3   
    >>> for (a, *b, c) in [(1, 2, 3, 4), (5, 6, 7, 8)]:
    ...    print(a, b, c)
    ...1 [2, 3] 4
       5 [6, 7] 8
    

    range反復器
    rangeは反復器で、必要に応じて要素が生成されます
    >>> list(range(-5, 5))
    [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4]
    
    >>> list(range(0, len(S), 2))
    [0, 2, 4, 6, 8, 10]
    
    >>> for i in range(3):
    ...     print(i, 'Pythons')
    ...0 Pythons
       1 Pythons
       2 Pythons
     
    #     
    >>> L = [1, 2, 3, 4, 5]
    >>> for i in range(len(L)):     # Add one to each item in L
    ...     L[i] += 1               # Or L[i] = L[i] + 1
    ...
    >>> L
    [2, 3, 4, 5, 6]
       
    

    zipパラレル反復器
    >>> L1 = [1,2,3,4]
    >>> L2 = [5,6,7,8]
    
    >>> zip(L1, L2)
    
    
    >>> list(zip(L1, L2))             # list() required in 3.0, not 2.6
    [(1, 5), (2, 6), (3, 7), (4, 8)]
    
    >>> for (x, y) in zip(L1, L2):
    ...     print(x, y, '--', x+y)
    ...1 5 -- 6
       2 6 -- 8
       3 7 -- 10
       4 8 -- 12
    

    zipによる辞書の構築
    # python2.2 before
    >>> keys = ['spam', 'eggs', 'toast']
    >>> vals = [1, 3, 5]
    >>> list(zip(keys, vals))[('spam', 1), ('eggs', 3), ('toast', 5)]
    >>> D2 = {}
    >>> for (k, v) in zip(keys, vals): D2[k] = v
    ...
    
    >>> D2
    {'toast': 5, 'eggs': 3, 'spam': 1}
    
    #python 2.2 later
    >>> keys = ['spam', 'eggs', 'toast']
    >>> vals = [1, 3, 5]
    >>> D3 = dict(zip(keys, vals))
    
    >>> D3
    {'toast': 5, 'eggs': 3, 'spam': 1}
    

    Enumerate関数
    Enumerate関数はジェネレータを返します.オブジェクトは簡単に言えば、次の組み込み関数によって呼び出されるnextメソッドがあり、ループで反復するたびに1つの(index,value)メタグループが返されます.
    >>> S = 'spam'
    >>> for (offset, item) in enumerate(S):
    ...     print(item, 'appears at offset', offset)
    ...s appears at offset 0
       p appears at offset 1
       a appears at offset 2
       m appears at offset 3