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(枚举) 对象。

python 复制代码
list_test = [1, 3, 5, 7, 9]
for idx, value in enumerate(list_test):
    print('idx:', idx, '  ', 'value: ', value)

输出:

powershell 复制代码
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,从大到小排序。
python 复制代码
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))

输出:

powershell 复制代码
[('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 排好序后要绑定一个对象(赋值)。

python 复制代码
list_test = [("a", 3), ("c", 5), ("b", 4)]
d_list_test = sorted(list_test, key=lambda x: x[1])

字典是无序的,但是可以用列表的sort()方法进行排序。

python 复制代码
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、列表元素计数

python 复制代码
import collections

numbers = [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、 有序序列的插入与查找

python 复制代码
import bisect

a = [1, 2, 2, 3, 5, 8]
pos = bisect.bisect(a, 7)
print(pos) # 5

bisect.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

python 复制代码
cnt = {2: 3, 4: 2, 1: 1, 3: 1}
print(max(cnt.keys(), key=cnt.get)) # 2

力扣题目练习

两数之和

https://leetcode.cn/problems/two-sum/description/

python 复制代码
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        num_dict = {}
        for idx, value in enumerate(nums):
            num_dict[value] = idx
        
        for 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/

python 复制代码
# 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
相关推荐
cup1110 分钟前
[开源] Meta Assistant / 告别命令行,我为一堆 Python 脚本做了一个 Windows 任务栏的“家”
windows·python·工具·nuitka·脚本运行
绿算技术11 分钟前
万卡推理集群存储选型分析:从核心架构到应用视角
大数据·科技·算法·架构
小小编程路1 小时前
Python 还有容器类型互转、进制转换、字符编码转换
开发语言·windows·python
想吃火锅10051 小时前
【leetcode】1.两数之和js版
javascript·算法·leetcode
Samooyou1 小时前
RAG项目案例--02在线检索&过滤流水线
人工智能·python·ai·全文检索·检索
动能小子ohhh1 小时前
DocForge平台的设计与开发--文件上传接口的实现
开发语言·人工智能·python·langchain·ocr·fastapi
ab_dg_dp2 小时前
Android 17+ 提取 AIDL 生成 Java 文件的实用脚本
android·java·python
net3m332 小时前
一阶软件低通滤波器算法
人工智能·算法
夏语灬2 小时前
cryptography:Python 密码学标准库的终极选择
开发语言·python·密码学