Python-day 14三目演算、導出式、再帰、匿名、内蔵関数

28488 ワード

一、三項演算子
 if...else...   
: if...else... ,

cmd = input('cmd: ')
print('       ') if cmd.isdigit() else print('        ')
​
​
a = 20
b = 30
res = a if a > b else b  #    
print(res)
​
​
res = 'b   ' if a > b else 'a   '  #    
print(res)

 
           

a=20
b=30

res=a if a>b else b
print(res)
res='b   'if a>b else 'a    ' #    
print(res)
                     
    :           ,                 :   a          

 
二、導出式
     :[v for v in iterable]
dic = {
       'a': 1, 'b': 2, 'c': 3}  # => [('a', 1), ('b', 2), ('c', 3)]
res = [(k, v) for k, v in dic.items()]
     :{k: v fro k, v in iterable}
ls = [('a', 1), ('b', 2), ('c', 3)]  # => {'a': 1, 'b': 2, 'c': 3}
res = {k: v for k, v in ls}
dic={
       'a':1,'b':2,'c':3}    #         [('a',1),('b',2),('c',3)]

res=[(k,v)for k,v in dic.items()]
print(res)  #     [('a',1),('b',2),('c',3)]

print('=================================')

     

res=((k,v)for k,v in dic.items())
            
print(tuple(res))  #    :(('a', 1), ('b', 2), ('c', 3))


     
ls=[('a',1),('b',2),('c',3)] # >>>{'a':1,'b',2,'c:3'}
res={k:v for k,v in ls }
print(res)  #     {'a': 1, 'b': 2, 'c': 3}

  
rang(10)       
res_ls=[arg for arg in range(10)]
print(res_ls) #     [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
res_dic={
       'a':arg for arg in range(10)}
print(res_dic)  #     {'a': 9}
res_dic={arg:'a' for arg in range(10)}
print(res_dic) #     {0: 'a', 1: 'a', 2: 'a', 3: 'a', 4: 'a', 5: 'a', 6: 'a', 7: 'a', 8: 'a', 9: 'a'}


                  
res_dic={v:k for k,v in enumerate('abc')}
print(res_dic)

#     {'a': 0, 'b': 1, 'c': 2}

 
三、再帰

: ,
: ( 、 )
: ( )




import sys
sys.setrecursionlimit(100)  #         (    )
print(sys.getrecursionlimit())

count=0
def a():
    global  count
    count+=1
    if count>50:
        return
    a()
a()


        :        ,      
def b():
    c()
def  c():
    d()
def d():
    b()

b()
   :
         ,       ,           ,          
   :              


def get_age(num):  #    
    if num==1:
        return 58
    age=get_age(num-1)-2
    return  age
res=get_age(5)
print(res)



  
def factorial(num):
    if num==1:
        return 1
    temp=num*factorial(num-1)#  >>>> 5*4*3*3*1
    return temp
res=factorial(5)
print(res)

# 5 !=5*4! 4!=4*3!......2!=2*1

 
四、匿名関数


lambda | ()| return

lambda x,y:x+y
            

          
f=lambda  x,y:x+y
print(f)
print(f(10,20)) #   30

f=lambda x,y:(x+y,x-y)  # (x+y,x-y)            
print(f)
print(f(10,20))  #  (30  ,-10)

 
1、                 ,              ,        
2、         :                ,           ,           


res=(10,20,50,30)
print(res)

res=max({10,20,50,30})
print(res)

print('====================================')
def fn(arg):
    print(arg)
    return  arg
ls =[100,200,50,10]
res=max(ls,key=fn)
print(res)  #    :100 200

print('====================================')
res1=max(ls,key=lambda   ele:ele)
print(res1)
#     200

 
五、内蔵関数
# max

iterable = [1, 5, 3, 2, 7]
res = max(iterable, key=lambda x: x)  #   :          ;   :     
print(res)

#     
iterable = {
    'Bob': 12000,
    'Tom': 37000,
    'Jerry': 76000,
    'Zero': 120,
}
res = max(iterable, key=lambda x: iterable[x])  # x:    k     :     
print(res)

iterable = {
    'Bob': {
      'no': 100, 'salary': 12000},
    'Tom': {
      'no': 200, 'salary': 37000},
    'Jerry': {
      'no': 50, 'salary': 76000},
    'Zero': {
      'no': 150, 'salary': 120},
}
res = max(iterable, key=lambda k: iterable[k]['no'])
print(res)
res = max(iterable, key=lambda k: iterable[k]['salary'])
print(res)


# min
iterable = {
    'Bob': [100, 12000],
    'Tom': [200, 37000],
    'Jerry': [50, 76000],
    'Zero': [150, 120],
}
res = min(iterable, key=lambda k: iterable[k][1])  #     
print(res)

 
#  sorted
res = sorted([1, 3, 4, 2, 5], key=lambda x: x, reverse=True)
print(res)

iterable = {
    'Bob': [100, 12000],
    'Tom': [200, 37000],
    'Jerry': [50, 76000],
    'Zero': [150, 120],
}
res = sorted(iterable, key=lambda x: iterable[x][0])  #  no  
print(res)

 
# map:  
res = map(lambda x: x + 2, [12000, 36000, 27000, 21000, 10000])
print(list(res))

from functools import reduce
# reduce:   
res = reduce(lambda f, n: f * n, [1, 2, 3, 4, 5])
print(res)

 
#
# classmethod() #    
# staticmenthod()  #    
# super()
# object()

#     
# globals()
# locals()

#   
# getattr()
# setattr()
# delattr()

#      <=>       
# exec()

# enumerate()
# isintance()
# len()
# max()
# min()
# open()
# range()
# type()
print('-----------------------------------')

 
#   
print(abs(-1))  #    
print(pow(2, 3, 3))  # 2 ** 3 % 3
print(sum([1, 2, 3]))  #   
print(divmod(100, 30))  # 100 30      

#       
print(all([1, 2, 'abc']))  #       
print(any([1, "", None]))  #       
filter(lambda x: x % 2 == 0, [1, 2, 3, 4, 5])  #         

#      
print(ascii('
-*..
')) print(repr('
-*..
')) print(r'
-*..
') # print(10) print(bin(10)) print(oct(10)) print(hex(10)) # bool() str() bytes() chr() ord() range(1, 5) # [1, 2, 3, 4] ''' def aaa():pass print(callable(aaa)) #

 


#         ''  ,        
s = 'print(123)'
# print(s)
eval(s)
s = '{"a": 1}'
res = eval(s)
print(res['a'])

res = divmod(100, 30)  # 100 30      
print(res)

res = filter(lambda x: x % 2 == 0, [1, 2, 3, 4, 5])
print(list(res))

#    
res = format(97, 'b')
print(res)

#       
print(globals())
def a():
    a = 10
    b = 20
    print(locals())
a()


# hash    
# print(hash([]))  #       hash
# print(hash(()))  #      hash
# import uuid
# print(uuid.uuid4())


open()
range()

 
    
t = max(iter, fn)  max(iter lambda k: i[k])
    temp = None
    for k in iter:
        res = fn(k)
        # res       
        # temp   res        
    return temp

  
転載先:https://www.cnblogs.com/zhouqinmei/p/10656587.html