Python 初学(二)

周末过去了。

继续新的学习,首先今天把上周学的东西复习了一下,有关于list 相关的,还有tuple,这两者前者可以随意的增删改查,一般用符号标志位[ ] ,而后者一旦初始化就不能修改了,符号标志()

dict ,优点为查找速度快,缺点是占内存。

list ,优点占内存少,缺点查找和插入的时间随着元素的增加而增加。

set  ,和dict类似,也是一组key的集合,但不存储value。由于key不能重复,所以,在set中,没有重复的key。

还有就是函数的调用,有参无參函数,递归函数等等。

复习完成后,学了新的知识。关于python一些特性。

切片,相当于把一个组合分开(根据条件,见demo),取一个list或tuple的部分元素

迭代,通过for循环来遍历这个list或tuple,这种遍历我们称为迭代。

列表生成器,range 

详见demo实例,今天脑子有点晕晕乎乎的,不在状态,可能跟昨晚没睡好有很大关系。。。

# by Fan 20180702
# 复习上周内容,继续学习后面内容
mettts = ['Michael', 'Bob', 'Tracy']
print(mettts)
print(mettts[1])
print(mettts.pop(2))
print(mettts)
mettts2 = ['Michael', 'Bob', 'Tracy']

# 知识点
# list是一种有序的集合,可以随时添加和删除其中的元素  列表符号标志()
# 有序列表叫元组:tuple,一旦初始化就不能修改    列表符号标志 []

# 请利用循环依次对list中的每个名字打印出Hello, xxx!:
L = ['Bart', 'Lisa', 'Adam']
for x in L:
	print('Hello,'+x+'!')
for x in range(3):
	print('Hello,' + L[x] + '!')
a=0
while a<len(L):
	print('Hello,' + L[a] + '!')
	a=a+1

# dict词典   类似于map      优点:查找速度快 缺点:占内存
d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
print(d['Michael'])
# 插入数据
d['Adam'] = 67
print(d)
# 查询 Thomas 是否存在
# 第一种方法
print('Thomas' in d)
if 'Thomas' in d:
	print('=====Thomas,存在')
else:
	print('=====Thomas,不存在')
# 第二种方法
# print(d.get('Thomas'))
if d.get('Thomas')=='None':
	print('=====Thomas,存在')
else:
	print('=====Thomas,不存在')

# list  缺点:查找和插入的时间随着元素的增加而增加;
# 优点:占用空间小,浪费内存很少。

# set  set和dict类似,也是一组key的集合,但不存储value。由于key不能重复,所以,在set中,没有重复的key。
f=set([1,2,2,2,3,4,4,5])
print(f)
f.add(0)
print(f)


# 函数的调用
# 在我看来 函数相当于 java中的void ,有参无參等等类似,只是语法结构稍微不同罢了
#
def test():
	print('hello')
def test2(x):
	print('hello'+x)
def test3(y,m):
	print('hello '+y+' '+m)
# 有参 无參
test()
test2('xxx')
test3('me','you')

# 递归函数  return
def fact(n):
    if n==1:
        return 1
    return n * fact(n - 1)
fact(1)

# ###########################################以上为上周回顾################################################
# 新知识点
# python特性
# 切片
BB = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']
BB[0:3]
print(BB[0:2])   # (切片 :)
'ABCDEFG'[0:3]
# 迭代
d = {'a': 1, 'b': 2, 'c': 3}
for key in d:
	print( key )
# 列表生成器
LL= list(range(1, 11))
print(LL)

# 生成[1x1, 2x2, 3x3, ..., 10x10] 之和
AA = []
for x in range(1, 11):
	AA.append(x * x)
print(AA)   # 普通方法
CC = [x * x for x in range(1, 11)]
print(CC)   # 生成器方法


# 高阶函数概念   ==》一个函数就可以接收另一个函数作为参数
# map  map()函数接收两个参数,一个是函数,一个是Iterable,map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回。
list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
# reduce  序列[1, 3, 5, 7, 9]变换成整数13579
from functools import reduce
def fn(x, y):
	return x * 10 + y
print(reduce (fn, [1, 3, 5, 7, 9]))


猜你喜欢

转载自blog.csdn.net/mapeifan/article/details/80887336