Python for Senior Lesson 7

v1.0.0

2016.11 by David.Yi

本次内容要点

  • 测验
  • 测验题目讲解

In [10]:
# if else 的用法

x, y = 4, 5

smaller = x if x > y else y

print(smaller)


5

In [26]:
# 匿名函数 lambda 用法

a =  lambda x, y=2 : x + y*3 
print(a(3) + a(3, 5))


27

In [29]:
# list 的 count方法

l = ['tom', 'steven', 'jerry', 'steven']
print(l.count('tom') + l.count('steven'))


3

In [30]:
# os 用法
# 计算目录下有多少文件

import os

a = os.listdir()
print(len(a))


3

In [10]:
# 获得路径或者文件的大小
import os

os.path.getsize('/Users')


Out[10]:
204

In [9]:
# 列表生成式用法
# 在列表生成式后面加上判断,过滤出结果为偶数的结果

n = 0
for i in [x * x for x in range(8, 11) if x % 2 == 0]:
    n = n + i
print(n)


164

In [14]:
# 简化调用方式
# 省却了 try...finally,会有 with 来自动控制

filename = 'test.txt'

with open(filename, 'r') as f:
    print(f.read())


hello
byebye

In [38]:
# python 有趣灵活的变量定义

first, second, *rest = (1,2,3,4,5,6,7,8)
print(first + second + rest[2])


8

In [42]:
# for continue 举例
# 以及 等于 不等于 或者 的逻辑判断

for l in 'computer':
    if l != 't' or l == 'u':
        continue
    print('letter:', l)


letter: t

In [12]:
# 找到符合 x*x + y*y == z*z + 3 的 x y z
# 多种循环

n = 0

for x in range(1,10):
    for y in range(x,10):
        for z in range(y,10):
            if x*x + y*y == z*z:
                print(x,y,z)
                n= n + 1
print('count:',n)


3 4 5
count: 1

In [7]:
# python 内置函数 

print(max((1,2),(2,3),(2,4),(2,4,1)))


(2, 4, 1)

In [8]:
l = ['amy', 'tom', 'jerry ']
for i, item in enumerate(l):
    print(i, item)


0 amy
1 tom
2 jerry 

In [ ]: