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

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

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] = 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/
在这里插入图片描述

# 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
  • 9
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

他是只猫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值