jupyter notebook基础命令与python常用函数
本文最后更新于 1771 天前,其中的信息可能已经有所发展或是发生改变。
# 多行输出结果
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"

1. 关于jupyter cell里的命令,命令都需要写在最前面

1.0 帮助命令: ?以及%magic等

1.1 使用%%, 指定解释器(包括终端命令)

%%cmd,%%bash,%%HTML,%%python2,%%ruby

cmd: 注释: 冒号, 双冒号以及rem 换行: ^(横向数字6的第二功能)
powershell: 注释: #, <# #> 换行: `(横向数字左边的单撇)
Linux bash: 注释: # 换行: \

%%cmd :注释
python --version ::注释
Microsoft Windows [版本 10.0.17134.191]
(c) 2018 Microsoft Corporation。保留所有权利。
G:\Programming\Python\2-advance_tutorial>python --version ::注释
G:\Programming\Python\2-advance_tutorial>
Python 3.6.4 :: Anaconda, Inc.
!python --version ::注释
Python 3.6.4 :: Anaconda, Inc.

1.2 使用%%writefile,会将命令后所有内容写入文件:

%%writefile printName.py
print('test cell writefile2')
a = 2
b = 3
print('sum of a and b: ': a + b)
Writing printName.txt

1.3 使用%pycat,会读取文件内容显示:

%pycat printName.py
`print('test cell writefile2')`
`a = 2`
`b = 3`
`print('sum of a and b: ': a + b)`

1.4 使用%load,载入外部脚本,执行此命令后此命令会被注释:

%load ./printName.py

1.5 使用%%time,cell内代码的单次运行时间信息

%%time
import time
time.sleep(1)
Wall time: 1 s

2. dir

dir([object]): object — 对象、变量、类型

dir() 函数不带参数时,返回当前范围内的变量、方法和定义的类型列表;
带参数时,返回参数的属性、方法列表。如果参数包含方法__dir__(),该方法将被调用。
如果参数不包含__dir__(),该方法将最大限度地收集参数信息。

因下面代码输出太长故截去。可自己使用来查看

dir()  # 获得当前模块的属性列表
dir([ ])  # 查看列表的方法
dir('s')  # 查看字符串的方法
import time
dir(time)

有时在学习一个新的库时不可避免地要看库包括哪些函数,如果全部输出 dir 信息就很长了,可以使用列表生成式来过滤下。

import tensorflow as tf

# 过滤掉类中__开头的魔法方法
[item for item in dir(tf.keras.optimizers) if not item.startswith('__')]

# 只输出类(一般第一个字母大写, 就用此条件来做评判)
[item for item in dir(tf.keras.optimizers) if item[0].isupper()]
['Adadelta',
 'Adagrad',
 'Adam',
 'Adamax',
 'Nadam',
 'Optimizer',
 'RMSprop',
 'SGD']

3. 异常捕获: try-except-else-finally

try:
    1 / 0
except Exception as e:
    '''异常的父类,可以捕获所有的异常'''
    print('error code: ', e, " 0不能被除")
else:
    '''保护不抛出异常的代码'''
    print("没有异常")
finally:
    print("finally: 最后总是要执行我")
`'异常的父类,可以捕获所有的异常'`
`error code:  division by zero  0`不能被除
`finally`: 最后总是要执行我

4. 字符串格式化函数 — format()

4.1 位置指定

# 不指定位置,默认顺序
'{} {}'.format('hello', 'world')

# 设置指定位置
'{0} {1}'.format('hello', 'world')
'{1} {0} {1}'.format('hello', 'world')
'hello world'
'hello world'
'world hello world'

4.2 参数指定

# 1. 参数指定
str = 'user_name: {name}, user_birth: {birth}'
str.format(name='Planck', birth=1858)

# 2. 通过字典设置参数
user_info = {'name': 'Planck', 'birth': 1858}
str.format(**user_info)

# 3. 通过列表索引设置参数
user_list = ['Planck', '1858']
'user_name: {0[0]}, user_birth: {0[1]}'.format(user_list)
# []前的0不能省略
'user_name: Planck, user_birth: 1858'
'user_name: Planck, user_birth: 1858'
'user_name: Planck, user_birth: 1858'

4.3 数字的格式化

"{:.2f}".format(3.1415926)  # 保留小数点后两位
"{:+.2f}".format(3.1415926)  # 带正负符号保留小数点后两位
"{:.0f}".format(3.1415926)  # 不保留小数点
"{:0>2d}".format(5)  # 数字补零 (填充左边, 宽度为2)
"{:x<4d}".format(5)  # 数字补零 (填充右边, 宽度为2)
"{:,}".format(10000000)  # 以逗号分隔的数字格式
"{:.2%}".format(0.25)  # 百分比格式
'{:b}'.format(11)
'{:d}'.format(11)
'{:o}'.format(11)
'{:x}'.format(11)
'{:#x}'.format(11)
'{:#X}'.format(11)
'3.14'
'+3.14'
'3'
'05'
'5xxx'
'10,000,000'
'25.00%'
'1011'
'11'
'13'
'b'
'0xb'
'0XB'

4.4 大括号的转义 — 双大括号

"{} 对应的位置是 {{0}}".format("hhh")
'hhh 对应的位置是 {0}'

评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇