Python-反復

1002 ワード

#  
#     list    tuple        。

#        for                 。

# list   tuple        

#    dict    
d = {'a':1, 'b':2, 'c':3}

# dict key   
for key in d:
    print(key)# a,b,c

# dict        ,                

# dict    value dict.values()
for value in d.values():
    print(value)#1,2,3

# dict    key   value  dict.items()
for key,value in d.items():
    print(key,value)
    # a 1
    # b 2
    # c 3


#              
for ch in 'ABC':
    print(ch)
    # A
    # B
    # C

#        ,      for      。

#               ?
#    collections     iterable   
from collections import Iterable
isinstance('abc',Iterable) # str        True
isinstance([1,2,3],Iterable) # list       True
isinstance(123,Iterable) #           False

# list   -      ,        
for i,value in enumerate(['A','B','C']):
    print(i,value)
# 0 A
# 1 B
# 2 C

#           
for x,y in [(1,1),(2,4),(3,9)]:
    print(x,y)
# 1 1
# 2 4
# 3 9