python基础知识
python基础语法
python基础精讲 http://t.csdnimg.cn/HdKdi
本专栏主要针对python基础语法,帮助学习者快速接触并掌握python大部分最重要的语法特征。
1、基本数据类型和变量
2、分支结构与循环结构
3、函数与异常处理
4、类与模块
5、文件读写
通过本专栏可以快速掌握python的基础语法。
补充函数:
1、 enumerate函数
- 1、enumerate()是python的内置函数;
- 2、enumerate在字典上是美剧、列举的意思;
- 3、功能:将一个可遍历的数据对象(如列表、元组、字典和字符串)组合成一个索引序列,同时列出数据下标和数据(索引 值),一般配合for循环使用。
语法
enumerate(sequence, [start=0])
参数
sequence – 一个序列、迭代器或其他支持迭代对象。
start – 下标起始位置。
返回 enumerate(枚举) 对象。
list_test = [1, 3, 5, 7, 9]
for idx, value in enumerate(list_test):print('idx:', idx, ' ', 'value: ', value)
输出:
idx: 0 value: 1
idx: 1 value: 3
idx: 2 value: 5
idx: 3 value: 7
idx: 4 value: 9
2、sorted高阶函数
高阶函数在python中是一个非常有用的功能函数,所谓高阶函数就是一个函数可以用来接收另一个函数作为参数,这样的函数叫做高阶函数。
如果要处理的数据内的元素不是一维的,而是二维的甚至是多维的,那要怎么进行排序呢?这时候,sorted()函数内的key参数就派上用场了!从帮助信息上可以了解到,key参数可传入一个自定义函数。
sorted函数包含三个参数:
sorted(可迭代对象,key=函数名,reverse=False/True)
- 参数一:一个可迭代的数据集。
- 参数二:一个key函数,以一定的算法对参数一中的元素(某数值或字符串等)进行修改和计算。
- 参数三:reverse=False,从小到大;reverse=True,从大到小排序。
list_test = [("a", 3), ("c", 5), ("b", 4)]
print(sorted(list_test, key=lambda x: x[1]))
dict_test = {'a': 3, "c": 5, "b": 4}
print(sorted(dict_test.items(), key=lambda x: x[1], reverse=False))
print(sorted(dict_test.items(), key=lambda x: x[1], reverse=True))
输出:
[('a', 3), ('b', 4), ('c', 5)]
sorted(list_test, key=lambda x: x[1])根据列表中元素的第二个数字进行排序(从小到大)
[('a', 3), ('b', 4), ('c', 5)]
sorted(dict_test.items(), key=lambda x: x[1], reverse=False)
按字典的值进行排序(从小到大)
[('c', 5), ('b', 4), ('a', 3)]
sorted(dict_test.items(), key=lambda x: x[1], reverse=True)
按字典的值进行排序(从大到小)
sorted 排好序后要绑定一个对象(赋值)。
list_test = [("a", 3), ("c", 5), ("b", 4)]
d_list_test = sorted(list_test, key=lambda x: x[1])
字典是无序的,但是可以用列表的sort()方法进行排序。
dict_test = {'a': 3, "c": 5, "b": 4}
L = list(dict_test.items())
print(L) # [('a', 3), ('c', 5), ('b', 4)]
L.sort(key=lambda x: x[1], reverse=True)
print(L) # [('c', 5), ('b', 4), ('a', 3)]
3、列表元素计数
import collectionsnumbers = [1, 2, 3, 3, 2, 6, 1, 4, 5]
cnt = collections.Counter(numbers)
print(cnt) # Counter({1: 2, 2: 2, 3: 2, 6: 1, 4: 1, 5: 1})colors = ['red', 'blue', 'red', 'red', 'blue']
c = collections.Counter(colors)
print(dict(c)) # {'red': 3, 'blue': 2}
4、 有序序列的插入与查找
import bisecta = [1, 2, 2, 3, 5, 8]
pos = bisect.bisect(a, 7)
print(pos) # 5bisect.insort(a, 4)
print(a) # [1, 2, 2, 3, 4, 5, 8]bisect.bisect_left(a, 2) # 插入左侧
bisect.bisect_right(a, 2) # 插入右侧
5、 取字典最大value值对应key
cnt = {2: 3, 4: 2, 1: 1, 3: 1}
print(max(cnt.keys(), key=cnt.get)) # 2
力扣题目练习
两数之和
https://leetcode.cn/problems/two-sum/description/

class Solution:def twoSum(self, nums: List[int], target: int) -> List[int]:num_dict = {}for idx, value in enumerate(nums):num_dict[value] = idxfor idx, value in enumerate(nums):if target- value in num_dict and idx != num_dict[target - value]:return [idx, num_dict[target - value]]
二叉树的层序遍历
https://leetcode.cn/problems/binary-tree-level-order-traversal/description/

# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:if not root:return []#定义一个双端队列queue = deque()res = []# 将根节点加入到队列中queue.append(root)while queue:level_nodes = []queue_size = len(queue)for i in range(queue_size):node = queue.popleft()level_nodes.append(node.val)if node.left:queue.append(node.left)if node.right:queue.append(node.right)res.append(level_nodes)return res