Skip to content

Instantly share code, notes, and snippets.

@duangsuse
Last active October 24, 2025 09:22
Show Gist options
  • Select an option

  • Save duangsuse/519411ab618ee57350ee2df93d33f58e to your computer and use it in GitHub Desktop.

Select an option

Save duangsuse/519411ab618ee57350ee2df93d33f58e to your computer and use it in GitHub Desktop.
Five .ipynb tutorial

Five .ipynb Language Tutorial

Thanks for contribution 🤗:

https://github.com/ShixiangWang/iLearning/blob/master/study/Python/learnPython/搞定Python基本操作.ipynb https://github.com/rajathkmp/Python-Lectures/blob/master/03.ipynb https://jupyter.org/try-jupyter/lab/index.html?fromURL=https://gist.githubusercontent.com/kenjyco/69eeb503125035f21a9d/raw/learning-python3.ipynb https://github.com/jamwine/Python-Beginners-Guide/blob/master/Learn%20Python%20in%20Jupyter%20Notebook.ipynb https://github.com/cs231n/cs231n.github.io/blob/master/python-colab.ipynb

for i in {2..6}; do printf " [🦄](https://jupyter.org/try-jupyter/lab/index.html?fromURL=https://gist.githubusercontent.com/duangsuse/519411ab618ee57350ee2df93d33f58e/raw/$i.ipynb)"; done

open a link above, CtrlV, ShiftEnter to run code below.

# <3 Python is REALLY simple, differ from MOST popular languages eg. Java C PHP Ruby 
# 💯 CtrlL https://hellogithub.com/en/report/tiobe 

# No "$" or "-" for var_x/defX/ClassX Names, no ^[0-9] at start.
# indentation & case sensitive, use Tab / Shift+Tab / ?var for docs

["It's not from TOML.io !"]
name = "Alice"      # String
age = 30            # Integer, 10//3 is 3
usdt = 19.99        # Float (USE 1999 FOR BALANCE)
is_active = True    # use with if bool(x):
hex2 = 0xdeadbeef   # int, 0xHex format

prices = {"Apple": 1.99, "Banana": 0.99}
fruits = ["Apple", "Banana", "Cherry"]
top1_fruit = fruits[i:=0]  # try i in range(0, < 3), or row[0:3] slice (supports -1=len()-1)

Composing flow

Compose statement literal containing API callgraph(': block' s) & vartree(GC values), reuse app functions with def(vars):

subprocess.getoutput

n=3 3 3
Hello 5
typed 5
world 5
[('Hello', 5), ('typed', 5), ('world', 5)] [('Hello', 5), ('typed', 5), ('world', 5)]

list(kv)=['Hello', 'typed', 'world']
kv={}
kv['Hello'] = 5
kv['typed'] = 5
kv['world'] = 5
two十(3)=5 666
two十(3)=5 669
More
# for(n=0, i=0;i<3;i+=1) n+=i
n = 0
for i in (rn := range(0, 3)):
  n += i

print(f"{n=}", sum(i + 0 for i in range(0, 3)), sum(rn))

words = "Hello typed  world  ".split(" ")
stdo = []
for w in words:
  if w != "":
    print(w, len(w))
for w in words:
  stdo.append((w, len(w))) if w != "" else None

print(stdo, kv := [(u, len(u)) for u in words], end="\n" * 2)

"deleteMe" or kv.pop(-1)  # , retWhenNone
kv = dict(kv)  # vartype shadowing
print(f"{list(kv)=}")  # = [*kv]
"duck🦆" or kv.pop("typed")

print("kv={}")  # 👎 C-style boilerplates
for col in kv.items():
  k, v = map(repr, col)  # json-compat literal_eval?
  if "explicit":
    k, v = (repr(u) for u in col)
  print(f"kv[{k}] = {v}")


def make_十(n):
  return lambda x: x + n


two十 = make_十(2)
print(f"{two十(3)=}", two十(664))

from argparse import Namespace


def cell_十(n=0):  # constructor(var n)
  def javaSAM(step):
    nonlocal n  # 👍 Py: no let-var style declarations, no (this.n)
    n += step
    return n

  return Namespace(inc=javaSAM)


two十 = cell_十(2).inc
print(f"{two十(3)=}", two十(664))

x = int(input("Please enter an integer: "))
if x < 0:
  x = 0
  print("Negative changed to zero")
elif x == 0:
  print("Zero")
elif x == 1:
  print("Single")
else:
  print("More")

# Let's extract the input(stdin.line),
# and make print a 'callback' by return(str) to sys callstack


def numKind(num):
  match num:
    case 0: it = "Zero"
    case 1: it = "Single"
    case x if x < 0:
      it = f"Negative ({x})"
    case _: it = "Normal"
  return it
  # it = match num: or "match num as it" are unsupported.


def tryInt(s: "123"):
  try:
    return int(s)
  except:
    return None


while "REPL":
  n = tryInt(input("integer: ").strip())
  if not n and n != 0:
    break
  # ^ Oops, NaN means 'invalid input', (0) ALSO DOES? so could nan be Falsey? .: bool(math.nan)
  print(numKind(n))

For spreadsheet guys

import io, pandas as pd
import matplotlib.pyplot as plt

STORE = """csv
Apple,Banana,Cherry
1,2,3
1.99,0.99,2
"""

# module_KV, class, def/arg:Type, (lambda nonlocalVars, codetree..) are ALL DICT AND 'k=v's in Python3.
for k in globals():
  if not all(c.isupper() for c in k):
    continue  # if /^[A-Z]+$/: replaceIt()  # tool regex101.com
  ext, mem = eval(f"{k}").split("\n", 1)  # v with(globalThis) of module.py
  exec(f"{k} = pd.read_{ext}(io.StringIO(mem))")


def main():
  df = STORE
  aapl_sales = df[df["Apple"] > 1]
  all = df.sum()
  # df.to_excel("out_store.xlsx", index=False)
  display(*vars().keys())
  display(*vars().values())

  df["Sale"] = df["Apple"] + df["Banana"]
  df["Sale"].plot(kind="line")
  plt.title("Units Sold Over Time")
  plt.show()


main()

For API designer, metaprogramming

#def With(u, f):  call eg.  With(Box(1), lambda x: x.As(x.v+1)), too long
def With(u):
  def PipeBy(f): f(u); return u
  return PipeBy

@With({})
def js(u):
  u['A'] = 1

print(js) # Yeah, @decorator are just fncall.  cout<< are operator<<(call), printf() are syscall(write,fd=0)
# They're FAKE SYNTAX, but idioms are not constant.

from dataclasses import dataclass, field
def data(T):
  'Trick: create vartree containers w/o def __init__ or call([],{})'
  {setattr(T, k, field(default_factory=v if isFn else v.copy)) for k,v in T.__annotations__.items() if (isFn:=callable(v))or hasattr(v,'copy')}
  return dataclass(T)

@data
class UserQueue:
  id: list
  usd: dict
  def onBuy(u, id):
    u.id.append(id)
    u.usd[id]=100
  def _repr_markdown_(u):
    get_ipython().__class__.__name__
    #^ https://ipython.readthedocs.io/en/stable/config/integrating.html
    return "".join(f"- [{me}]() **\\${u.usd[me]/100}**\n" for me in u.id)



@With(UserQueue())
def uq(u):
  [u.onBuy(id) for id in "Amy Jack Rose".split()]
  u.usd['Jack']=10_000
display(uq)

# got tired of `def try$Int` templates?
# cool @decorator to convert raise ValueError() to None
def tryFill(op, v0=None):
  def safe(*a, **kw):
    try: return op(*a, **kw)
    except: return (v0(a[0]) if callable(v0) else v0)
  return safe


@tryFill
def faulty(x):
  if x: raise x
  return x

if "": # edit, re-run!
    @tryFill
    def faulty(a):
      try:
        for x in a: raise x
      except TypeError: pass

tryFill(int)('abc'), tryFill(int, len)('abc')

HTTPd echo

4 major IO demo: EchoArgs, Counter, Checklist_DDL, SplitJoinWalk

first one (async Flask + cookie):

#sudo setcap 'cap_net_bind_service=+pie' /usr/bin/python3.*

from fastapi import FastAPI, Request
from fastapi.responses import Response
from uvicorn import run as bun
from pydantic import BaseModel, Field

I = FastAPI()

if "real world":

  @I.get("/login")
  async def setJsGlobal():
    # Create response with login message
    rpc = Response("Login successful. Session address set.")

    # Set session cookie with 1-day expiration
    rpc.set_cookie(
      key="USER",
      value="objectID",  # In production, use a hash(random+salt) token
      max_age=dur,
      expires=dur,
      path="/",  # Cookie available for HOST/*
      secure=False,  # Set to True in production with HTTPS
      httponly=True,  # Prevent XSS attacks
      samesite="lax",  # Prevent CSRF with modern browsers
    )
    return rpc

  class Blog(BaseModel):
    "try connect DB"

    id: int = Field(None, description="TBD, eg. UUID, auto-increment")
    slug: str = Field(min_length=4, max_length=15)
    html: str = Field(min_length=1, max_length=3000)  # no optional, age range


# @I.get("/{path:path}")
async def echo(path: str, u: Request):
  output = [
    f"curl $I/{path}",
    f"location.search: {u.query_params}",
    "Body: None (call PUT for write)\n\n",
    f"Client IP: {u.client.host}",
  ]
  auth(output, u)
  output.append("kwargs = {")
  for key, value in u.headers.items():  # try shorten!
    output.append(f"  {key} = {value}, ")
  output.append("}\n")

  return Response(content="\n".join(output), media_type="text/plain")


superFn = echo
@I.get("/{path}") # dont GET /
async def echo(
  path: str,
  q: str = "",
  p: int = 1,
  sort: str = "-1create_at",
  per_page: int = 100,
  u: Request = None,
):
  curs = (p - 1) * per_page
  res = await superFn(path, u)  # middleware are just "override fun" or pipes
  return Response(
    f"db.filter({q})[{curs}:{curs + per_page}].sort_({sort})\n".encode() + res.body
  )


@I.post("/{path}")
async def echo(path: str, u: Request):  # orderBy created, [0 1 2..]
  output = [
    "",
    f"location.search: {u.query_params}",
    f"Client IP: {u.client.host}",
  ]
  auth(output, u)  # try sort output!
  (output.append)("kwargs:")
  for key, value in u.headers.items():  # try shorten!
    output.append(f"  {key}: {value}")

  body = await u.body()
  output.append(f"\nBody ({len(body)} bytes/octects):")
  output.append(crud := body.decode("utf-8", errors="ignore"))
  output[0] = f"curl $I/{path} -d@'-' <<<{repr(crud)}"
  return Response(content="\n".join(output), media_type="text/plain")


if __name__ == "__main__":
  dur = 10 or 86400  # 24 hours in seconds
  foreign = {
    "objectID": f"Proxy.revocable(SQL_pointer,{dur}s)",
    None: "readonly, no-REST",
  }
  auth = lambda ln, u: ln.append(
    f"SK_ *(&api): {foreign.get(u.cookies.get('USER', None), 'expired')}"
  )
  bun(I, host="0.0.0.0", port=8080)
  if "fetch() fail":
    see = "https://fastapi.tiangolo.com/tutorial/cors/#use-corsmiddleware"
    see = "https://jsonplaceholder.typicode.com/"

if "f-string and let-match were not born" or "ES6 = uglify JS":
  from bottle import route, run, template

  @route('/hello/<name>')
  def index(name):
      return template('<b>Hello {{name}}</b>!', name=name)

  run(host='localhost', port=8080)
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 搞定Python基本操作(科学计算)\n",
"\n",
"学习资料为<http://www.jianshu.com/p/e17b397cff3c>及后续,感谢作者 MurphyWan。"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"其实之前也学习过Python的一些基本概念和操作,最近也时常有阅读廖雪峰的Python3教程,但这些基本概念的掌握和理解不是一朝一夕能够沉淀下来的,而我需要快速的能进入使用节奏。所以依靠这几篇博文学习练手。后续也需要继续深入学习Python概念与ipython。\n",
"\n",
"**如果你想要按照此笔记学习,请下载本文件,然后用jupyter notebook或线上的一些jupyter notebook打开编辑,自己运行试试。**"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Python基础知识\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 常用数据类型\n",
"\n",
"\n",
"|名称|表示|声明示例|\n",
"|--|--|--|\n",
"|整数|int|a=10|\n",
"|浮点数|float|b=3.14|\n",
"|复数|complex|c=1+2j|\n",
"|字符串|str|d=\"python\"|"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 算数运算符\n",
"\n",
"|名称|表示|声明示例|\n",
"|--|--|--|\n",
"|加法|+|a+b|\n",
"|减法|-|c-b|\n",
"|乘法|*|x*y|\n",
"|除法|/|x/z|\n",
"|取模|%|x%a|\n",
"|取幂|**|a**x|"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 练习"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"10"
]
},
"execution_count": 1,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"a = 10 # int\n",
"a"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"3.14"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"b = 3.14 # float\n",
"b"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"100"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"d = a ** 2 # a的乘方\n",
"d"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"<class 'int'>\n"
]
}
],
"source": [
"print(type(d)) # 返回d类型"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"<class 'float'>\n"
]
}
],
"source": [
"print(type(d/10)) # 返回d/10类型"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"<class 'float'>\n"
]
}
],
"source": [
"print(type(a/b)) # 返回a/b类型"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"<class 'float'>\n"
]
}
],
"source": [
"c = 3 # int\n",
"print(type(a/c)) # 返回a/c类型"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"<class 'float'>\n"
]
}
],
"source": [
"print(type(b*d)) # 返回bd类型"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 浮点数的精度"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"0.30000000000000004"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"0.1 + 0.2"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"这是二进制浮点的本质。\n",
"> 浮点数也就是小数,之所以称为浮点数,是因为按照科学记数法表示时,一个浮点数的小数点位置是可变的,比如,1.23x109和12.3x108是完全相等的。浮点数可以用数学写法,如1.23,3.14,-9.01,等等。但是对于很大或很小的浮点数,就必须用科学计数法表示,把10用e替代,1.23x109就是1.23e9,或者12.3e8,0.000012可以写成1.2e-5,等等。\n",
"\n",
">整数和浮点数在计算机内部存储的方式是不同的,整数运算永远是精确的(除法难道也是精确的?是的!),而浮点数运算则可能会有四舍五入的误差。\n",
"\n",
"> --- 摘自廖雪峰Python3教程"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"可以使用`rond()`函数控制显示精度,但也有一些意外,比如`round(9.995, 2)`返回9.99而不是10,因为9.995在存储时是稍小于9.995的。"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"9.99"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"round(9.995, 2)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"decimal Library可以给出精确的存储值,看下面的例子。"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"3.14\n",
"9.99\n",
"9.9949999999999992184029906638897955417633056640625\n"
]
}
],
"source": [
"import decimal # import decimal library\n",
"# display 2 decimal precision\n",
"print(round( 3.1415, 2)) \n",
"print(round(9.995, 2))\n",
"\n",
"print(decimal.Decimal(9.995))"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"He is a string. who are you?\n",
"['He', 'is', 'a', 'string.', 'Who', 'are', 'you?']\n",
"3\n",
"11\n",
"-1\n",
"He i\n",
"He|is|a|string.|Who|are|you?\n",
"www.google.com\n"
]
}
],
"source": [
"### 字符str的一些功能\n",
"t = \"He is a string. Who are you?\"\n",
"print(t.capitalize()) # 首字母大写\n",
"print(t.split()) # 分割字符\n",
"print(t.find('i')) # 查找字符i索引值\n",
"print(t.find('in'))\n",
"print(t.find('Python'))\n",
"print(t[0:4])\n",
"print(t.replace(' ', '|')) # 修改分隔符\n",
"w = 'http://www.google.com'\n",
"print(w.strip('http://')) # 删掉字符"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**注意Python的索引从0开始,不包括最后的位置。比如[0:4]是取得前4个子项。**"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 基本的数据结构\n",
"\n",
"|名称|表示|声明示例|\n",
"|--|--|--|\n",
"|元组|tuple|b=(1,2.5,'data')|\n",
"|列表|list|c=[1,2.5,'data']|\n",
"|字典|dict|d={'Name':'Kobe','Country':'US'}|\n",
"|集合|set|e=set(['u','d','ud','d','du'])|\n",
"\n",
"\n",
" 元组(tuple)只有几种方法可以更改。\n",
" 列表(list)比元组更灵活。\n",
" 字典(dict)是一个键值对存储对象。\n",
" 集合(set)是对象中唯一的无序集合对象。\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 列表的一些有用功能"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"<class 'list'>\n",
"[1, 2, 3.14, 'data', [4, 3]]\n",
"[1, 2, 3.14, 'beta', 'data', [4, 3]]\n",
"[1, 2, 3.14, 'beta', [4, 3]]\n"
]
}
],
"source": [
"l = [1, 2, 3.14, 'data'] # list\n",
"print( type(l))\n",
"l.append([4, 3]) # 添加列表\n",
"print(l)\n",
"l.insert(3, 'beta') # 在index 3前插入\n",
"print(l)\n",
"l.remove('data') # 删除\n",
"print(l)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 对象引用"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[5, 2, 3, 4]\n",
"[1, 2, 3, 4]\n"
]
}
],
"source": [
"x = [1, 2, 3, 4]\n",
"y = x\n",
"y[0] = 5\n",
"print(x)\n",
"\n",
"x = [1, 2, 3, 4]\n",
"z = x.copy()\n",
"z[0] = 5\n",
"print(x)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**注意上述两者引用方式的差异性,如果只是简单地使用`=`进行赋值,只是给地址添加了一个字符对象引用,上述`y`与`x`是指向同一个地址,所以改动`y`也会改动`x`。**"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 多维列表\n",
"\n",
"我们下面创建一个包含多行的列表。"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3]]\n",
"4\n"
]
}
],
"source": [
"a = [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3]]\n",
"print(a)\n",
"print(a[0][3])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"注意多维列表不是矩阵。"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 条件语句\n",
"\n",
"控制元素包括if, else, elif\n",
"\n",
"判断方式包括`>`,`<`,`==`,`>=`,`<=`"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[24, 16, 54]\n"
]
}
],
"source": [
"a = [24, 16, 54]\n",
"b = []\n",
"\n",
"if a[0] < a[1] or a[0] < a[2]:\n",
" b.append(a[0])\n",
" if a[1] < a[2]:\n",
" b.append(a[1])\n",
" b.append(a[2])\n",
" else:\n",
" b.append(a[2])\n",
" b.append(a[1])\n",
"\n",
"print(b)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 循环语句\n",
"\n",
"循环语句有不同的代码样式,这里列出最常用的两种:\n",
"\n",
"```python\n",
"# 1\n",
"for ... in ...: statement A\n",
"# 2\n",
"while ...: statement A\n",
"```"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2\n",
"4\n",
"5\n",
"25\n",
"8\n",
"64\n",
"5050\n"
]
}
],
"source": [
"# 举例\n",
"for i in range(2, 10, 3):\n",
" print(i)\n",
" l = i ** 2\n",
" print(l)\n",
" \n",
"a = 0\n",
"sumup = 0\n",
"while a < 100:\n",
" a += 1\n",
" sumup += a\n",
"print(sumup)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### break和continue\n",
"\n",
"- 你可以在循环语句中使用break关键字跳出循环。\n",
"- 你可以在循环语句中使用continue关键字暂停当前的循环执行后面的语句。"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"306\n"
]
}
],
"source": [
"# 举例\n",
"# 找第一个能被17整除的数\n",
"for i in range(300, 351):\n",
" if i % 17 == 0:\n",
" print(i)\n",
" break\n",
" else:\n",
" continue"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 循环语句嵌套\n",
"\n",
"就是循环中嵌套循环\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"```Python\n",
"for in range(10):\n",
" print(i)\n",
" for(j in range(5)):\n",
" print(j)\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 练习\n",
"\n",
"- 计算从1到1000的累积值\n",
"- 计算从1到1000的偶数之和"
]
},
{
"cell_type": "code",
"execution_count": 33,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"累积值为 402387260077093773543702433923003985719374864210714632543799910429938512398629020592044208486969404800479988610197196058631666872994808558901323829669944590997424504087073759918823627727188732519779505950995276120874975462497043601418278094646496291056393887437886487337119181045825783647849977012476632889835955735432513185323958463075557409114262417474349347553428646576611667797396668820291207379143853719588249808126867838374559731746136085379534524221586593201928090878297308431392844403281231558611036976801357304216168747609675871348312025478589320767169132448426236131412508780208000261683151027341827977704784635868170164365024153691398281264810213092761244896359928705114964975419909342221566832572080821333186116811553615836546984046708975602900950537616475847728421889679646244945160765353408198901385442487984959953319101723355556602139450399736280750137837615307127761926849034352625200015888535147331611702103968175921510907788019393178114194545257223865541461062892187960223838971476088506276862967146674697562911234082439208160153780889893964518263243671616762179168909779911903754031274622289988005195444414282012187361745992642956581746628302955570299024324153181617210465832036786906117260158783520751516284225540265170483304226143974286933061690897968482590125458327168226458066526769958652682272807075781391858178889652208164348344825993266043367660176999612831860788386150279465955131156552036093988180612138558600301435694527224206344631797460594682573103790084024432438465657245014402821885252470935190620929023136493273497565513958720559654228749774011413346962715422845862377387538230483865688976461927383814900140767310446640259899490222221765904339901886018566526485061799702356193897017860040811889729918311021171229845901641921068884387121855646124960798722908519296819372388642614839657382291123125024186649353143970137428531926649875337218940694281434118520158014123344828015051399694290153483077644569099073152433278288269864602789864321139083506217095002597389863554277196742822248757586765752344220207573630569498825087968928162753848863396909959826280956121450994871701244516461260379029309120889086942028510640182154399457156805941872748998094254742173582401063677404595741785160829230135358081840096996372524230560855903700624271243416909004153690105933983835777939410970027753472000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\n",
"偶数之和为 250500\n"
]
}
],
"source": [
"# 1\n",
"r = 1\n",
"for i in range(1,1001):\n",
" r = r * i\n",
"print(\"累积值为\",r)\n",
"\n",
"# 2\n",
"s = 0\n",
"for i in range(1, 1001):\n",
" if i % 2 == 0:\n",
" s = s + i\n",
"print(\"偶数之和为\",s)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 函数声明\n",
"\n",
"**函数定义**\n",
"\n",
"```python\n",
"def The_Name_of_Function(para1, para2):\n",
" ...\n",
" return Outcome\n",
"```\n",
"\n",
"**函数调用**\n",
"\n",
"```python\n",
"The_Name_of_Function(para1, para2)\n",
"```"
]
},
{
"cell_type": "code",
"execution_count": 34,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2\n"
]
}
],
"source": [
"# 举例,求两个变量最大值的函数\n",
"def MaxOfTwo(x1, x2):\n",
" if x1 >= x2:\n",
" return x1\n",
" else:\n",
" return x2\n",
" \n",
"a = 1\n",
"b = 2\n",
"c = MaxOfTwo(a, b)\n",
"print(c)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 默认参数\n",
"\n",
"我们可以为函数的参数提供默认值,例如:\n",
"```python\n",
"def MaxOfTwo(x1, x2 = 1):\n",
" ...\n",
" ```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 返回多个输出\n",
"\n",
"可以通过元组返回两个或多个输出:\n",
"\n",
"```python\n",
"def f (x1, x2, x3, ...):\n",
" ......\n",
" return(y1, y2, y3, ...)\n",
"\n",
"a1,b1,c1 = f(...)\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 读/写文件"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 内建open()方法\n",
"\n",
"要打开一个文件,使用Python内建的open()函数。 open()方法返回一个文件对象,最常用的一般使用两个参数。\n",
"\n",
"```python\n",
"file_object = open(filename, mode)\n",
"```\n",
"\n",
"这个mode参数可以是\n",
"\n",
" 'r' 只读模式(when the file will only be read)\n",
" 'w' 只写模式(与一个现存文件文件同名,则被清除)\n",
" 'a' 添加模式,即任意写入文件的数据都被自动添加到末尾\n",
" 'r+' 打开文件,可以读、写\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 创建文件\n"
]
},
{
"cell_type": "code",
"execution_count": 35,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"file = open('newfile.txt', 'w')\n",
"file.write('I am created for the course. \\n')\n",
"file.write('How about you?\\n')\n",
"file.write('How is your exam?')\n",
"file.close()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 读取一个文件"
]
},
{
"cell_type": "code",
"execution_count": 37,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"I am created for the course. \n",
"How about you?\n",
"How is your exam?\n",
"I am creat\n",
"I am created for the course. \n",
"\n",
"['I am created for the course. \\n', 'How about you?\\n', 'How is your exam?']\n"
]
}
],
"source": [
"file = open('newfile.txt', 'r')\n",
"# 输出整个文件\n",
"print(file.read())\n",
"file.close()\n",
"# 输出前10个字符\n",
"file = open('newfile.txt', 'r')\n",
"print(file.read(10))\n",
"file.close()\n",
"# 输出一行\n",
"file = open('newfile.txt', 'r')\n",
"print(file.readline())\n",
"file.close()\n",
"# 输出多行\n",
"file = open('newfile.txt', 'r')\n",
"print(file.readlines())\n",
"file.close()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 循环读取一个文件\n"
]
},
{
"cell_type": "code",
"execution_count": 38,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"I am created for the course. \n",
"\n",
"How about you?\n",
"\n",
"How is your exam?\n"
]
}
],
"source": [
"file = open('newfile.txt', 'r')\n",
"for line in file:\n",
" print(line)\n",
"file.close()"
]
},
{
"cell_type": "code",
"execution_count": 39,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"I am created for the course.\n",
"How about you?\n",
"How is your exam?\n"
]
}
],
"source": [
"# 上述输出的不是原文本,因为print的同时又加了一个'\\n'\n",
"file = open('newfile.txt', 'r')\n",
"for line in file:\n",
" print(line.strip())\n",
"file.close()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 添加文本"
]
},
{
"cell_type": "code",
"execution_count": 40,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"I am created for the course. \n",
"How about you?\n",
"How is your exam?\n",
"I am back again. \n",
"Do you miss me? \n",
"\n"
]
}
],
"source": [
"file = open('newfile.txt', 'a')\n",
"file.write('\\nI am back again. \\n')\n",
"file.write('Do you miss me? \\n')\n",
"file.close()\n",
"# 查看\n",
"file = open('newfile.txt', 'r')\n",
"# 输出整个文件\n",
"print(file.read())\n",
"file.close()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### with语句\n",
"\n",
"最好使用with()函数进行文本读写,它会自动关闭文件。\n",
"\n",
"```python\n",
"with(open(\"humpty.txt\") as f:\n",
" ...\n",
" ```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"这样即使读取时发生错误,也可以确保文件正确关闭。"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 进阶"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**用Numpy, Scipy, Matplotlib等模块进行计算,解决一些数学问题**"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 导入模块\n",
"\n",
"通过import关键字导入模块\n",
"\n",
"```python\n",
"import numpy\n",
"```\n",
"\n",
"用as关键字给模块一个简称\n",
"\n",
"```python\n",
"import numpy as np\n",
"```\n",
"\n",
"有时候我们不必导入整个模块,只要导入部分功能函数\n",
"\n",
"```python\n",
"from scipy.stats imports norm\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 练习\n",
"\n",
"尝试导入时间模块,用它获取计算机运行指定代码所需要的时间\n"
]
},
{
"cell_type": "code",
"execution_count": 41,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Time cost of funl is 0.000094\n"
]
}
],
"source": [
"import timeit\n",
"\n",
"def funl(x, y):\n",
" return x**2 + y**3\n",
"\n",
"t_start = timeit.default_timer()\n",
"z = funl(109.2, 367.1)\n",
"t_end = timeit.default_timer()\n",
"\n",
"cost = t_end - t_start\n",
"print('Time cost of funl is %f' %cost)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"我们会用到的模块有:\n",
"\n",
"- NumPy: 多维数组操作,高效的数学计算函数\n",
"- Matplotlib: 可视化\n",
"- SciPy: 大型库实现各种数值算法,例如:\n",
" - 线性和非线性方程解\n",
" - 优化\n",
" - 数值整合\n",
"- Sympy: 符号计算\n",
"- Pandas: 统计与数据分析"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Numpy"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### ndarray类型\n",
"\n",
"NumPy提供了一种新的数据类型:ndarray(n维数组)。\n",
"\n",
" 与元组和列表不同,数组只能存储相同类型的对象(例如只有floats或只有ints)\n",
" 这使得数组上的操作比列表快得多; 此外,数组占用的内存少于列表。\n",
" 数组为列表索引机制提供强大的扩展。\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 创建ndarray"
]
},
{
"cell_type": "code",
"execution_count": 43,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([2, 3, 6, 7])"
]
},
"execution_count": 43,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# 导入Numpy\n",
"import numpy as np\n",
"# 创建numpy数组\n",
"np.array([2,3,6,7])"
]
},
{
"cell_type": "code",
"execution_count": 44,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([ 2., 3., 6., 7.])"
]
},
"execution_count": 44,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"np.array([2,3,6,7.])\n"
]
},
{
"cell_type": "code",
"execution_count": 45,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([ 2.+0.j, 3.+0.j, 6.+0.j, 7.+1.j])"
]
},
"execution_count": 45,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"np.array([2,3,6,7+1j])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 创建均匀间隔的数组\n",
"\n",
"arrange:"
]
},
{
"cell_type": "code",
"execution_count": 47,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([0, 1, 2, 3, 4])"
]
},
"execution_count": 47,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"np.arange(5)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"range(start, stop, step)的所有三个参数即起始值,结束值,步长都是可以用的 另外还有一个数据的dtype参数"
]
},
{
"cell_type": "code",
"execution_count": 48,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([ 10., 30., 50., 70., 90.])"
]
},
"execution_count": 48,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"np.arange(10, 100, 20, dtype = float)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"linspace(start,stop,num)返回数字间隔均匀的样本,按区间[start,stop]计算:"
]
},
{
"cell_type": "code",
"execution_count": 49,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([ 0. , 0.625, 1.25 , 1.875, 2.5 ])"
]
},
"execution_count": 49,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"np.linspace(0., 2.5, 5)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 多维数组矩阵"
]
},
{
"cell_type": "code",
"execution_count": 57,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[1, 2, 3],\n",
" [4, 5, 6]])"
]
},
"execution_count": 57,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"a = np.array([[1, 2, 3],[4, 5, 6]])\n",
"a"
]
},
{
"cell_type": "code",
"execution_count": 58,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(2, 3)"
]
},
"execution_count": 58,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"a.shape"
]
},
{
"cell_type": "code",
"execution_count": 60,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"2"
]
},
"execution_count": 60,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"a.ndim"
]
},
{
"cell_type": "code",
"execution_count": 61,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"6"
]
},
"execution_count": 61,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"a.size"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 形状变化"
]
},
{
"cell_type": "code",
"execution_count": 62,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"import numpy as np\n",
"\n",
"a = np.arange(0, 20, 1) # 1维\n",
"b = a.reshape((4,5)) # 4行5列\n",
"c = a.reshape((20,1)) # 2维\n",
"d = a.reshape((-1, 4)) # -1:自动确定\n"
]
},
{
"cell_type": "code",
"execution_count": 63,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,\n",
" 17, 18, 19])"
]
},
"execution_count": 63,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"a"
]
},
{
"cell_type": "code",
"execution_count": 64,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[ 0, 1, 2, 3, 4],\n",
" [ 5, 6, 7, 8, 9],\n",
" [10, 11, 12, 13, 14],\n",
" [15, 16, 17, 18, 19]])"
]
},
"execution_count": 64,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"b"
]
},
{
"cell_type": "code",
"execution_count": 65,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[ 0],\n",
" [ 1],\n",
" [ 2],\n",
" [ 3],\n",
" [ 4],\n",
" [ 5],\n",
" [ 6],\n",
" [ 7],\n",
" [ 8],\n",
" [ 9],\n",
" [10],\n",
" [11],\n",
" [12],\n",
" [13],\n",
" [14],\n",
" [15],\n",
" [16],\n",
" [17],\n",
" [18],\n",
" [19]])"
]
},
"execution_count": 65,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"c"
]
},
{
"cell_type": "code",
"execution_count": 66,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[ 0, 1, 2, 3],\n",
" [ 4, 5, 6, 7],\n",
" [ 8, 9, 10, 11],\n",
" [12, 13, 14, 15],\n",
" [16, 17, 18, 19]])"
]
},
"execution_count": 66,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"d"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Size(N,),(N,1)和(1,N)是不同的!!!**\n",
"\n",
"\n",
" Size(N, )表示数组是一维的。\n",
" Size(N,1)表示数组是维数为2, N列和1行。\n",
" Size(1,N)表示数组是维数为2, 1行和N列。\n"
]
},
{
"cell_type": "code",
"execution_count": 68,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"55\n",
"55\n",
"[[ 1 2 3 4 5]\n",
" [ 2 4 6 8 10]\n",
" [ 3 6 9 12 15]\n",
" [ 4 8 12 16 20]\n",
" [ 5 10 15 20 25]]\n"
]
}
],
"source": [
"# 例子\n",
"import numpy as np\n",
"\n",
"a = np.array([1,2,3,4,5])\n",
"b = a.copy ()\n",
"\n",
"c1 = np.dot(np.transpose(a), b)\n",
"print(c1)\n",
"c2 = np.dot(a, np.transpose(b))\n",
"print(c2)\n",
"\n",
"ax = np.reshape(a, (5,1))\n",
"bx = np.reshape(b, (1,5))\n",
"c = np.dot(ax, bx)\n",
"print(c)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 使用相同元素填充数组\n"
]
},
{
"cell_type": "code",
"execution_count": 69,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([ 0., 0., 0.])"
]
},
"execution_count": 69,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"np.zeros(3)"
]
},
{
"cell_type": "code",
"execution_count": 70,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[ 0.+0.j, 0.+0.j],\n",
" [ 0.+0.j, 0.+0.j]])"
]
},
"execution_count": 70,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"np.zeros((2,2), complex)"
]
},
{
"cell_type": "code",
"execution_count": 71,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[ 1., 1., 1.],\n",
" [ 1., 1., 1.]])"
]
},
"execution_count": 71,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"np.ones((2,3))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 使用随机数字填充数组\n",
"\n",
"rand: 0和1之间均匀分布的随机数"
]
},
{
"cell_type": "code",
"execution_count": 72,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[ 0.64006312, 0.52507683, 0.19150809, 0.14512848],\n",
" [ 0.44435529, 0.54196468, 0.67622118, 0.28109175]])"
]
},
"execution_count": 72,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"np.random.rand(2, 4)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### randn: 均值为0,标准差为1的标准(高斯)正态分布"
]
},
{
"cell_type": "code",
"execution_count": 73,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[ 0.66849307, 0.52848045, -0.31279224, 1.53961143],\n",
" [-1.2584165 , 1.09309986, -0.16010106, -0.30071292]])"
]
},
"execution_count": 73,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"np.random.randn(2, 4)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 一维数组切片\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"以格式start:stop可以用来提取数组的片段(从开始到不包括stop)"
]
},
{
"cell_type": "code",
"execution_count": 74,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"a = np.array([0, 1, 2, 3, 4])"
]
},
{
"cell_type": "code",
"execution_count": 75,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([1, 2])"
]
},
"execution_count": 75,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"a[1:3]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"start可以省略,在这种情况下,它被设置为零(Notes:貌似留空更合适):"
]
},
{
"cell_type": "code",
"execution_count": 76,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([0, 1, 2])"
]
},
"execution_count": 76,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"a[:3]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"stop也可以省略,在这种情况下它被设置为数组长度:"
]
},
{
"cell_type": "code",
"execution_count": 77,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([1, 2, 3, 4])"
]
},
"execution_count": 77,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"a[1:]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"也可以使用负指数,具有标准含义:"
]
},
{
"cell_type": "code",
"execution_count": 78,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([1, 2, 3])"
]
},
"execution_count": 78,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"a[1:-1]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"整个数组:a或a [:]"
]
},
{
"cell_type": "code",
"execution_count": 80,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([0, 1, 2, 3, 4])"
]
},
"execution_count": 80,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"a"
]
},
{
"cell_type": "code",
"execution_count": 81,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([0, 1, 2, 3, 4])"
]
},
"execution_count": 81,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"a[:]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"按步长获取元素"
]
},
{
"cell_type": "code",
"execution_count": 82,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([0, 2, 4])"
]
},
"execution_count": 82,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"a[::2]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"-1的这个步骤可用于反转数组:"
]
},
{
"cell_type": "code",
"execution_count": 83,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([4, 3, 2, 1, 0])"
]
},
"execution_count": 83,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"a[::-1]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 二维数组切片\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"对于多维数组,索引是整数元组"
]
},
{
"cell_type": "code",
"execution_count": 84,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[ 0, 1, 2, 3],\n",
" [ 4, 5, 6, 7],\n",
" [ 8, 9, 10, 11]])"
]
},
"execution_count": 84,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"a = np.arange(12)\n",
"a.shape = (3, 4)\n",
"a"
]
},
{
"cell_type": "code",
"execution_count": 85,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"6"
]
},
"execution_count": 85,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"a[1, 2]"
]
},
{
"cell_type": "code",
"execution_count": 86,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"7"
]
},
"execution_count": 86,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"a[1, -1]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"索引的工作与列表完全相同"
]
},
{
"cell_type": "code",
"execution_count": 88,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([1, 5, 9])"
]
},
"execution_count": 88,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"a[:, 1] # 这是第二列"
]
},
{
"cell_type": "code",
"execution_count": 89,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([ 8, 9, 10, 11])"
]
},
"execution_count": 89,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"a[2, :]"
]
},
{
"cell_type": "code",
"execution_count": 90,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"6"
]
},
"execution_count": 90,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"a[1][2]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"不必明确提供尾随的冒号"
]
},
{
"cell_type": "code",
"execution_count": 91,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([ 8, 9, 10, 11])"
]
},
"execution_count": 91,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"a[2] # 按行"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"复杂点的索引"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"![](http://mmbiz.qpic.cn/mmbiz/nliazs07woqkq6aoUyEKB0WlJqwfFpSzZj4SpbZHGPibQcTv8YSMMbOWia0jWwqibGRJwMBricVIRlDZ6vlVqCLryGQ/640?wx_fmt=jpeg&wxfrom=5&wx_lazy=1)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 副本(copy)和视图(view)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
" 采用标准的list切片为其建立副本\n",
" 采用一个NumPy数组的切片可以在原始数组中创建一个视图。 两个数组都指向相同的内存。因此,当修改视图时,原始数组也被修改:\n"
]
},
{
"cell_type": "code",
"execution_count": 94,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([0, 1, 2, 3, 4])"
]
},
"execution_count": 94,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"a = np.arange(5)\n",
"a"
]
},
{
"cell_type": "code",
"execution_count": 95,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([2, 3, 4])"
]
},
"execution_count": 95,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"b = a[2:]\n",
"b"
]
},
{
"cell_type": "code",
"execution_count": 96,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([100, 3, 4])"
]
},
"execution_count": 96,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"b[0] = 100\n",
"b"
]
},
{
"cell_type": "code",
"execution_count": 98,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([ 0, 1, 100, 3, 4])"
]
},
"execution_count": 98,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"a # 对应位置变了"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"为避免修改原始数组,可以制作一个切片的副本"
]
},
{
"cell_type": "code",
"execution_count": 99,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([0, 1, 2, 3, 4])"
]
},
"execution_count": 99,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"a = np.arange(5); a"
]
},
{
"cell_type": "code",
"execution_count": 100,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([2, 3, 4])"
]
},
"execution_count": 100,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"b = a[2:].copy(); b"
]
},
{
"cell_type": "code",
"execution_count": 101,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([100, 3, 4])"
]
},
"execution_count": 101,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"b[0] = 100\n",
"b"
]
},
{
"cell_type": "code",
"execution_count": 102,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([0, 1, 2, 3, 4])"
]
},
"execution_count": 102,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"a"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 矩阵乘法\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"运算符 * 表示元素乘法,而不是矩阵乘法"
]
},
{
"cell_type": "code",
"execution_count": 104,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[ 1, 4],\n",
" [ 9, 16]])"
]
},
"execution_count": 104,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"A = np.array([[1, 2],[3, 4]])\n",
"A * A"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"使用dot()函数进行矩阵乘法:"
]
},
{
"cell_type": "code",
"execution_count": 105,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[ 7, 10],\n",
" [15, 22]])"
]
},
"execution_count": 105,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"np.dot(A, A)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"dot()方法也适用于矩阵向量(matrix-vector)乘法:"
]
},
{
"cell_type": "code",
"execution_count": 106,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([ 50, 110])"
]
},
"execution_count": 106,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"x = np.array([10, 20])\n",
"np.dot(A, x)"
]
},
{
"cell_type": "code",
"execution_count": 107,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([ 70, 100])"
]
},
"execution_count": 107,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"np.dot(x, A)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 将数组保存到文件\n",
"\n",
"savetxt()将表保存到文本文件。"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"这里我就照着拷贝下啦,不存了\n",
"\n",
"```python\n",
"In [1]: a = np.linspace(0. 1, 12); a.shape(3, 4); a\n",
"Out [1] :\n",
"array([[ 0. , 0.09090909, 0.18181818, 0.27272727],\n",
"[ 0.36363636, 0.45454545, 0.54545455, 0.63636364],\n",
"[ 0.72727273, 0.81818182. 0.90909091, 1.]])\n",
"\n",
"In [2] : np.savetxt(\"myfile.txt\", a)\n",
"```\n",
"\n",
"save()将表保存为Numpy“.npy”格式的二进制文件\n",
"\n",
"```python\n",
"In [3] : np.save(\"myfile\" ,a) \n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 将文本文件读入数组\n",
"\n",
"loadtxt()将以文本文件存储的表读入数组。\n",
"\n",
"```python\n",
" In [1] : tabla = np.loadtxt(\"data.txt\")\n",
" In [2] : table\n",
" Out[2] :\n",
" array ([[ 1.99000000e+03, -1.50000000e+00, 2.53000000e+01], \n",
" [ 1.9910000e+03, -3.2000000e+00, 2.12000000e+01]\n",
"\n",
"```\n",
"\n",
"默认情况下,loadtxt()假定列是用空格分隔的。 您可以通过修改可选的参数.Lines进行更改。 以(#)开头的行将被忽略。"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Numpy包含更高效率的功能\n",
"\n",
"\n",
"\n",
" Numpy包含许多常用的数学函数,例如:\n",
" np.log\n",
" np.maximum\n",
" np.sin\n",
" np.exp\n",
" np.abs\n",
"\n",
" 在大多数情况下,Numpy函数比Math包中的类似函数更有效,特别是对于大规模数据。\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.3"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment