码农知识堂 - 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

  • 相关阅读:
    View#post(Runnable)的执行流程
    【vulhub】PostGresql高权限命令执行漏洞复现(CVE-2019-9193)
    原始html和vue中使用3dmol js展示分子模型,pdb文件
    第二证券|多只公募基金损失惨重;储能板块低开高走
    【Pyqt5】windows和linux安装Pyqt5+designer
    pytest合集(11)— conftest.py文件
    百度知道APP心跳包分析-MD5字段(gzip + CRC32)
    VCS 工具学习笔记(1)
    《Beginning C++20 From Novice to Professional》第六章 Pointers and References
    17.(开发工具篇Gitlab)如何在Gitlab配置ssh key
  • 原文地址:https://blog.csdn.net/DOITJT/article/details/126702774
  • 最新文章
  • 攻防演习之三天拿下官网站群
    数据安全治理学习——前期安全规划和安全管理体系建设
    企业安全 | 企业内一次钓鱼演练准备过程
    内网渗透测试 | Kerberos协议及其部分攻击手法
    0day的产生 | 不懂代码的"代码审计"
    安装scrcpy-client模块av模块异常,环境问题解决方案
    leetcode hot100【LeetCode 279. 完全平方数】java实现
    OpenWrt下安装Mosquitto
    AnatoMask论文汇总
    【AI日记】24.11.01 LangChain、openai api和github copilot
  • 热门文章
  • 十款代码表白小特效 一个比一个浪漫 赶紧收藏起来吧!!!
    奉劝各位学弟学妹们,该打造你的技术影响力了!
    五年了,我在 CSDN 的两个一百万。
    Java俄罗斯方块,老程序员花了一个周末,连接中学年代!
    面试官都震惊,你这网络基础可以啊!
    你真的会用百度吗?我不信 — 那些不为人知的搜索引擎语法
    心情不好的时候,用 Python 画棵樱花树送给自己吧
    通宵一晚做出来的一款类似CS的第一人称射击游戏Demo!原来做游戏也不是很难,连憨憨学妹都学会了!
    13 万字 C 语言从入门到精通保姆级教程2021 年版
    10行代码集2000张美女图,Python爬虫120例,再上征途
Copyright © 2022 侵权请联系2656653265@qq.com    京ICP备2022015340号-1
正则表达式工具 cron表达式工具 密码生成工具

京公网安备 11010502049817号