您的位置:首页 > 编程语言 > Python开发

Python学习记录_Day010总结复习+列表+集合+元组+字典

2018-03-08 21:02 603 查看

总结和复习

函数

"""
def f(a=0, b=0):
return a+b

f()
f(1)
f(1, 2)
"""

def f(*args):
total = 0
for val in args:
total += val
return total

mylsit = [1, 3, 5, 10, 20]
print(f(*mylist)
作用域 - LEGB
a = 100 # 尽量避开使用全局变量(迪米特法则)

def f():
global a #全局变量a
a = 200
b = 'hello'

def g():
nonlocal b # 嵌套变量b
b = 'good'

模块

对函数的分类管理,函数的设计应该遵守单一执着原则

字符串

列表

mylist = [x ** 2 for x in range(1,10]
mylist = mylist + [20, 30]
print(mylist)

内存管理

Python使用的自动内存管理,垃圾回收 栈 - 变量 - 地址 - 对象的引用 堆 - 真正的对象 id() is 静态区

知识点

1.列表

lists = [1, 2, 3, 4, 5]
lists = [0] * 5
lists = [0 for x in range(5)]
lists = [[]]

2.元组

tuple1 = (1, 2, 3)

3.集合:& ,|,-,+,^交集,并集等运算

# 集合的元素不会重复
set1 = {1,1,2,2,3}

# 输出{1,2,3}

4.集合,元组,列表可以互相转换,对于无序的集合,当他通过sorted函数排序后,会自动变成列表

5.字典

def main():
dict1 = {'name': '秦国宇', 'age':38, 'gender': True}
print(dict1['name'])
print(dict1['age'])
print(dict1['gender'])
dict1['name'] = '啊实打实'
print(dict1)
for x in dict1:
print(x, '----->',dict1[x])

if __name__ == '__main__':
main()

6.练习:

杨辉三角
def main(rows):
"""
杨辉三角
:param rows: 行数
:return:
"""
list1 = [1]
list2 = list1[:]
print(list1[0])
for _ in range(rows - 1):
for index in range(len(list1)):
if index + 1 < len(list1):
list2[index + 1] = list1[index] + list1[index + 1]
else:
list2.append(1)
list1 = list2[:]
for i in range(len(list2)):
print('%3d' % list2[i], end='  ')
print()
输出结果:
1
1    1
1    2    1
1    3    3    1
1    4    6    4    1
1    5   10   10    5    1
1    6   15   20   15    6    1
1    7   21   35   35   21    7    1
1    8   28   56   70   56   28    8    1
1    9   36   84  126  126   84   36    9    1
螺旋数列:
def work_two(num):
lists = [[0 for x in range(num)] for x in range(num)]
direction = 'right'
start = 1
cols = 0  # 列
rows = 0  # 行
circle = 1  # 初始圈数
while start <= (num*num):
if direction == 'right':
lists[rows][cols] = start
if cols >= num - circle:
direction = 'down'
continue
cols += 1
if direction == 'down':
lists[rows][cols] = start
if rows >= num - circle:
direction = 'left'
continue
rows += 1
if direction == 'left':
lists[rows][cols] = start
if cols <= circle - 1:
direction = 'up'
continue
cols -= 1
if direction == 'up':
lists[rows][cols] = start
if rows - 1 <= circle:
direction = 'right'
circle += 1
rows -= 1
start += 1
for i in range(num):
for j in range(num):
print('%3d' % lists[i][j], end='  ')
print()
输出结果:
1    2    3    4    5
16   17   18   19    6
15   24   25   20    7
14   23   22   21    8
13   12   11   10    9
最后,今天的知识点真的太多了,还有就是在最后一道题中,这个螺旋数列,确实把我的脑阔都整大了,大概梳理了一下今天的知识点,发现自己可能还是只有在列表方面要更加熟练一些,今天的博客可能在明天我还会继续补充
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: