练习题1

s='hello alex alex say hello sb sb'

 l=s.split()
 dic={}
 for item in l:
     if item in dic:
        dic[item]+=1
     else:
         dic[item]=1
 print(dic)

运行结果:计算每个元素出现的次数
{'hello': 2, 'alex': 2, 'say': 1, 'sb': 2}

  

def fib(max):
     n,a,b =0,0,1
     while n < max:
         yield b
         a,b =b,a+b
         n = n+1
     return 'done'
 for i in fib(6):
     print(i)
运行结果:输出斐波那契数列

1
1
2
3
5
8

  

s = "ajldjlajfdljfddd"
s = set(s)
s = list(s)
print(s)
s.sort(reverse = False)
print(s)
#print(type(s.sort(reverse = False)))   #报错
s.sort(reverse = True)
print(s)
res = "".join(s)
print(res)

运行结果:去重并按序输出
['j', 'd', 'f', 'a', 'l']
['a', 'd', 'f', 'j', 'l']
['l', 'j', 'f', 'd', 'a']
ljfda

  

#列表推导式求列表所有奇数并构造新列表
a =  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
res = [i for i in a if i%2 == 1]
print(res)

运行结果:
[1, 3, 5, 7, 9]
#lambda的使用
g = lambda x,y=0,z=0: x+y+z
print(g(1))
print(g(3,4,7))

运行结果:
1
14

(g = lambda x,y=0,z=0: x+y+z)(1,2,3)
运行结果:
6

 runoob测验-运算符

def Foo(x):
    if (x==1):
        return 1
    else:
        return x+Foo(x-1)

print(Foo(4))

运行结果:10
原文地址:https://www.cnblogs.com/Nicloe2333/p/10558524.html