前言
在pandas库学习过程发现一些偏冷的python的基础知识,有些是疑问没有准确的答案,有些是理解总结,先记录下来现在想法和理解。
一、嵌套空列表意义?
list1 = []
定义一个空列表
list2=[ [ ] , [ ] , [ ] ]
定义一个嵌套的空列表
list1=[[],[],[]]
list1[0].append(1)
list1[0].append(2)
list1[1].append(3)
list1[1].append(4)
list1[2].append(5)
list1[2].append(6)
print(list1) # [[1, 2], [3, 4], [5, 6]]
列表是一组数据,而嵌套列表可以理解是一组有层级结构的数据。
嵌套的空列表意义就像把结构先定义下来后面补充?感觉跟编码的规范相关增加了可读性?
二、列表和运算符
列表相加等同于list.extend()函数
列表与数字相乘等于列表元素复制后增加。
list_1 = [1, 2]
list_2 = [3, 4]
print(list_1 + list_2) # [1, 2, 3, 4]
print(list_1 * 2) # [1, 2, 1, 2]
# print(list_1-list_2) # 不支持类型
# print(list_1*list_2) # 不支持类型
# print(list_1/list_2) # 不支持类型
# print(list_1 + 2) # 不支持类型
# print(list_1 - 2) # 不支持类型
# print(list_1 / 2) # 不支持类型
运算符也算函数?可以支持重载重新定义规则,在pandas中重新定义后,列与列相加就是元素之间相加。
l1 = pd.DataFrame([1, 2, 3])
l2 = pd.DataFrame([3, 4, 5])
l3 = l1 + l2
l4 = (l1 + l2) / 2
print(l1)
print(l2)
print(l3)
print(l4)
三、字典嵌套后自上而下和自下而上修改键对应值。
s = {'a': {"A": "1"}} # 我们想得到{'a': {'A': '1', 'B': 2}}
# 自上而下
s['a']={'A': '1', 'B': 2}
print(s)
# 自下而上
ss = s['a'] # 取出关键字对应的下一层字典
ss['B'] = 2 # 增加本层字典的关键字和对应的值
s['a'] = ss # 本层字典当作上一层关键字对应的值。
print(s)
做编程试题,答案看不懂,研究一番才明白,至于有没有用,自己思考。
dic1 = {}
def set(key, value):
dic1[key] = value
def setdic(hkey, key, value):
hash_set = dic1.get(hkey)
# if dic1[hkey] is None: #[]取值找不到关键字报错,要用get方法
if hash_set is None:
hash_set = {key: value}
set(hkey, hash_set)
else:
hash_set[key] = value
set(hkey, hash_set)
setdic('puzzle', 'hello', 'world!')
setdic('puzzle', 'monkey', 'king!')
setdic('puzzle', 'tomorrow', 'is another day')
setdic('puzzle', 'good', 'bye!')
print(dic1)
# {'puzzle': {'hello': 'world!', 'monkey': 'king!', 'tomorrow': 'is another day', 'good': 'bye!'}}
四、双星号字典形参使用场景(待补)
从如何写好一个函数增加其拓展性思考(待补)
def my_func_1(x, **kwargs):
if kwargs.get('plus_3'):
return my_func_2(x, **kwargs) + 3
return my_func_2(x, **kwargs)
def my_func_2(x, **kwargs):
# Imagine that the function did more work
if kwargs.get('square'):
return x ** 2
# If you decided to add cube as a parameter
# you only need to change the code here:
if kwargs.get('cube'):
return x ** 3
return x
print(my_func_1(10, **{'square': 1}))
print(my_func_1(10, cube=1))
print(my_func_1(10, plus_3=1, cube=1))
五、编程思想(待补)
函数封装(内部代码管理方式)、类的封装(内部代码管理方式)思考耦合问题,加层方式解决强依赖,达到解耦。(待补)
六、库的学习方法(待补)
总结
学习方法要注重理解,理解才能记忆。笔记作用是让自己快速回到当时思考环境可以接着思考。