码农知识堂 - 1000bd
  •   Python
  •   PHP
  •   JS/TS
  •   JAVA
  •   C/C++
  •   C#
  •   GO
  •   Kotlin
  •   Swift
  • Python Language Megadoc


    • Python is not compiled (run directly)
    • Python is statically typed (the types of the variables cannot change)
    • Python is not strongly typed (do not declare types)
    • Python does not use curly braces (use tabs and indentations)
    • Boolean values are now True and False
    • Logic operator are now and or
    • Run pip install on commandline to install packages
      • In Google Colab, you can run command line arguments in the Python notebook by prefacing the commands with ! -- e.g. !pip install
    • Use \ at the end of a line to indicate continue on the next line

    Importing

    • Importing library modules
      • import math
      • from math import sqrt
      • import numpy as np
    • Importing file as a module
      • import homework1 // import homework1 file for the first time
      • import importlib; importlib.reload(homework1) // after the first time, use importlib

    List

    Iteration using enumerate()

    Python enumerate(): Simplify Looping With Counters – Real PythonOnce you learn about for loops in Python, you know that using an index to access items in a sequence isn't very Pythonic. So what do you do when you need that index value? In this tutorial, you'll learn all about Python's built-in enumerate(), where it's used, and how you can emulate its behavior.https://realpython.com/python-enumerate/#using-pythons-enumerate

    List comprehensions

    • Replace loop when doing very simple operations on each element
      • only one line of code
    • Creates a new list with manipulated list values
    • Syntax: 

      newlist = [expression for item in iterable if condition == True]

    • e.g. squares = [ x*x for x in nums if x>10] // square each element in list nums

    Transform list to dictionary or sets

    • List of tuples to dictionary

                    

              

    •  List to set

            

            

    Move a list item to position

    l.insert(newindex, l.pop(oldindex))

    Dictionary

    Dictionary Comprehension

    example:

    • groceries = {"milk": 2, "egg": 2}
    • more_groceries = { k:v*2 for k,v in groceries.items if ....}

    https://www.datacamp.com/tutorial/python-dictionary-comprehension

    Priority Queue

    • Defulat order: non-decreasing
    1. import queue as Q
    2. // declare a priority queue
    3. q = Q.PriorityQueue()
    4. // enqueue
    5. q.put(10)
    6. q.put(1)
    7. q.put(5)
    8. while not q.empty():
    9. print(q.get()) // dequeue

    Strings

    • Use single quotes ′ double quotes ”

    • """ triple quotes to comment blocks of code

    Access length

    • len(s)

    Access charAt(index)

    • s[index]
    • s[-1] -- counts from the end, so last char of the string

    Access substring

    • s[1:4] -- from 1 to 3, excluding the end
    • s[1:4:2] -- from 1 to 3, but stride 2, i.e. skipping every other character
    • s[2:] -- from 2 to end
    • s[2:10000] -- from 2 to end
    • s[:2] -- from start to 1, excluding the end
    • s[:] / s[::] -- copy the entire string
    • s[::-1] -- copy and reverse the string

    Splitting a string

    • s.split(' ') -- split by space (only one space)

    Remove spaces

    • s.strip() -- removes all spaces (front and back) from a string

    Compare strings

    • s == 'abc' -- compare values

    Converting to string

    • str(123) -- '123'

    For loop

    for ... in ... :

            print();

    Specifying range

    • range(5) -- 0 to 4, excluding the end
    • range(0,5) -- -- 0 to 4, excluding the end

    Iterate through elements

    • for x in arr                   // java like for each loop
    • for i in range(len(list)) // java like for loop

    Iterate through dictionary

    • for key, vallue in dict.items()

    Iterate through pairs of things

    • for (x, y) in [(a,b) , (c,d)]

    Iterator

    • A type of objects that have the __iter__() magic method
    • Iterator objects can be iterated in for loops
    • Throws StopIteration exception when ending

    e.g. list, dict, etc.

    Create custom iterator class

             

    Usage with handling end of iteration

    1. l = list(range(5))
    2. it = l.__iter__()
    3. try:
    4. print(it.__next__())
    5. except:
    6. print("nothing left") # prompting list end

    ** same thing happens in a python for each loop

                    

    Generators

    A special type of function that return a lazy iterator. These are objects that you can loop over like a list.

    • basically an iterator, but with less code
    • stop and continue execution for each 'yield'
    • stores the execution state for future consumption
    • returns a generator object
      • any function with a yield in the body

    How to Use Generators and yield in Python – Real PythonIn this step-by-step tutorial, you'll learn about generators and yielding in Python. You'll create generator functions and generator expressions using multiple Python yield statements. You'll also learn how to build data pipelines that take advantage of these Pythonic tools.https://realpython.com/introduction-to-python-generators/

    Benefits

    • Less code than basic iterator
    • Memory efficient -- reduces memory usage (it doesn't store a list in memory)
    • Good for one-pass summing/counting
    • Good for infinite seqence
    • Bad for individual values (debugging)

    Define a generator function

    • e.g. an infinite sequence
    1. def f():
    2. num = 0
    3. while True:
    4. yield num
    5. num += 1

    Using a generator function

    • nums = f() // num is a generator object
    • Get next item
      • next(nums) OR
      • nums.__next__() // using the under-the-hood iterator method
    • for i in f(): // keep yielding all the items

    Handling the end of an iteration

  • 相关阅读:
    前后端(react+springboot)服务器部署
    R语言:主成分分析PCA
    Spring boot 使用QQ邮箱进行一个验证登入
    Leetcode 754. 到达终点数字
    【陕西理工大学-数学软件实训】数学实验报告(8)(数值微积分与方程数值求解)
    13年老鸟整理,性能测试技术知识体系总结,从零开始打通...
    如何在Linux系统中安装MySQL数据库
    MongoDB中的分布式集群架构
    Idea Debug断点太多 启动太慢
    Golang中的type关键字
  • 原文地址:https://blog.csdn.net/DOITJT/article/details/126702774
  • 最新文章
  • 【JVM】编译执行与解释执行的区别是什么?JVM 使用哪种方式?
    用 Hashids 优雅解决 C 端自增 ID 暴露问题
    V8引擎 精品漫游指南--Ignition篇(上) 指令 栈帧 槽位 调用约定 内存布局 基础内容
    LLVM Pass快速入门(四):代码插桩
    milkup:桌面端 markdown AI续写和即时渲染
    基于项目工程构建SBOM(软件物料清单)的研究
    鸿蒙应用开发UI基础第二节:鸿蒙应用程序框架核心解析与实操
    .NET 中如何快速实现 List 集合去重?
    扣子Coze实战:从0到1打造抖音+小红书热点监控智能体
    浅谈数据访问层
  • 热门文章
  • 十款代码表白小特效 一个比一个浪漫 赶紧收藏起来吧!!!
    奉劝各位学弟学妹们,该打造你的技术影响力了!
    五年了,我在 CSDN 的两个一百万。
    Java俄罗斯方块,老程序员花了一个周末,连接中学年代!
    面试官都震惊,你这网络基础可以啊!
    你真的会用百度吗?我不信 — 那些不为人知的搜索引擎语法
    心情不好的时候,用 Python 画棵樱花树送给自己吧
    通宵一晚做出来的一款类似CS的第一人称射击游戏Demo!原来做游戏也不是很难,连憨憨学妹都学会了!
    13 万字 C 语言从入门到精通保姆级教程2021 年版
    10行代码集2000张美女图,Python爬虫120例,再上征途
小工具 小游戏
Copyright © 2022 侵权请联系2656653265@qq.com    京ICP备2022015340号-1

京公网安备 11010502049817号