素数、杨辉三角、封装结构和集合操作(15)——IPython使用和封装解构

IPython使用

帮助

?  ##Ipython的概述和简介

help(name)  ##查询指定名称和帮助

obj?  ##列出obj对象的详细信息

obj??  ##列出更详细的信息

特殊变量

_表示前一次输出

__表示前二次输出

___表示前三次输出

_oh 输出历史

_oh
{4: 100, 5: 100, 6: 100, 10: [1, 2, 3, 4]}

c=_
c
[1, 2, 3, 4]

pwd 当前目录

_dh 目录历史

pwd
'C:\Users\Administrator'

cd c:
c:

_dh
['C:\Users\Administrator', 'c:\']

shell命令

!command调用shell命令

!ls
'ls' is not recognized as an internal or external command,
operable program or batch file.

!dir
 Volume in drive C has no label.
 Volume Serial Number is A494-4369

 Directory of c:

2019/10/12  17:34    <DIR>          FusionCloud6.1
2019/10/15  16:33    <DIR>          installtool
2019/10/28  15:16    <DIR>          Program Files
2019/10/31  18:02    <DIR>          Program Files (x86)
2019/08/12  14:45    <DIR>          Users
2019/10/31  17:55    <DIR>          vms
2019/11/01  09:25    <DIR>          Windows
               0 File(s)              0 bytes
               8 Dir(s)  29,517,729,792 bytes free

魔术方法

IPython的内部实现,和操作系统无关

使用%百分号开头,IPython内置的特殊方法

%magic格式

  %开头是line magic

  %%开头是cell magic

%timeit statement

def primenumber():
    n=9
    row=[1]*n  ##一次性开辟全部空间
    for i in range(n):
        old=1
        for j in range(i//2):
            va=old+row[j+1]
            old=row[j+1]  ##row[j+1]将被覆盖,通过变量old先将row[j+1]保留
            row[j+1]=va
            if i !=2*(j+1):
                row[i-(j+1)]=row[j+1]
            else:
                pass 
    #           print('***')
    #    print(row[:i+1])  ##切片打印列表

%timeit primenumber()
16.7 µs ± 348 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%%timeit setup_code

%%timeit
n=9
row=[1]*n  ##一次性开辟全部空间
for i in range(n):
    old=1
    for j in range(i//2):
        va=old+row[j+1]
        old=row[j+1]  ##row[j+1]将被覆盖,通过变量old先将row[j+1]保留
        row[j+1]=va
        if i !=2*(j+1):
            row[i-(j+1)]=row[j+1]
        else:
            pass 
#           print('***')
#    print(row[:i+1])  ##切片打印列表
17.4 µs ± 1.69 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)
def prime1(limit):
    primenumbers=[2]
    for x in range(3,limit,2):
        for i in range(3,int(x**0.5)+1,2):
            if x%i==0:
                break
        else:
            primenumbers.append(x)
    return primenumbers

%timeit prime1(100)
75.1 µs ± 1.14 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

def prime2(limit):
    primenumbers=[3,5]
    x=7
    step=4
    while x<limit:
        if x%5!=0:
            for i in range(3,int(x**0.5)+1,2):
                if x%i==0:
                    break
            else:
                primenumbers.append(x)
        x+=step
        step=4 if step==2 else 2
    return primenumbers

%timeit prime2(100)
51.1 µs ± 1.45 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

 %%js、%%javascript在cell中运行js脚本

%%js
console.log('a'+20)

%%js
alert('a'+20)

封装和解构

封装

将多个值使用逗号分割,组合在一起

本质上,返回一个元组,只是省掉了小括号

t3=1,2    ##将1和2封装成元组
t3
(1, 2)

type(t3)
tuple

交换

a=1
b=2

temp=a
a=b
b=temp

等价于

a,b=b,a    ##等号右边使用封装,等号左边使用解构

解构

把线性结构的元素拆开,并顺序的赋给其它变量

左边接纳的变量数要和右边解开的元素个数一致

a,b=1,2
a,b
(1, 2)

a,b=(1,2)
a,b
(1, 2)

a,b=[1,2]
a,b
(1, 2)

a,b={1,2}
a,b
(1, 2)

a,b={'a':10,'b':20}    ##非线性结构也可以解构
a,b
('a', 'b')

a,b={1,2,3}    ##左右两边数量必须一致
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-79-14e2385ba548> in <module>
----> 1 a,b={1,2,3}

ValueError: too many values to unpack (expected 2)

使用 *变量名 接受,但不能单独使用

被 *变量名 收集后一定组成一个列表

a,*b={1,2,3}
a,b
(1, [2, 3])

[a,b]=1,2
a,b
(1, 2)

[a,b]=(1,2)
a,b
(1, 2)

a,b={1,2}
a,b
(1, 2)

lst=list(range(1,21,2))
lst
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

a,*b,c=lst
a,b,c
(1, [3, 5, 7, 9, 11, 13, 15, 17], 19)

*b=lst
  File "<ipython-input-87-67fc0332f20f>", line 4
SyntaxError: starred assignment target must be in a list or tuple

*b,c=lst
b,c
([1, 3, 5, 7, 9, 11, 13, 15, 17], 19)

a,*b,*c,d=lst
  File "<ipython-input-89-6b365811e22f>", line 4
SyntaxError: two starred expressions in assignment

a,*b,c='abcdefghijklmn'
a,b,c
('a', ['b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm'], 'n')

a,b,c,*d=1,2,3
a,b,c,d
(1, 2, 3, [])

type(d)
list

解构嵌套元素

a,b,c=[1,[2,3],4]
a,b,c
(1, [2, 3], 4)

a,b,c,d=[1,[2,3],4]
a,b,c,d
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-95-b018a82d86b2> in <module>
----> 1 a,b,c,d=[1,[2,3],4]
      2 a,b,c,d

ValueError: not enough values to unpack (expected 4, got 3)

a,(b,c),d=[1,[2,3],4]
a,b,c,d
(1, 2, 3, 4)

丢弃变量

如果不关心一个变量,就可以定义变量的名字为_

_是一个合法的标识符,也可以作为一个有效的变量使用,但是_这个变量本身无任何语义,没有任何可读性,定义成下划线就是希望不要被使用

Python中很多库,都使用这个变量,使用十分广泛,请不要在不明确变量作用域的情况下,使用_导致和库中_冲突

lst=1,2,3,4
a,*_,c=lst
a,c,_
(1, 4, [2, 3])

lst=list(range(10))##取出第二个,第四个,倒数第二个元素
_,a,_,b,*_,c,_=lst
a,b,c
(1, 3, 8)

练习

1.从lst=[1,(2,3,4),5]中,提取4出来

lst=[1,(2,3,4),5]
_,(*_,a),_=lst
a
4

2.环境变量JAVA_HOME=/usr/bin(字符串),返回环境变量名和路径

vir='JAVA_HOME=/usr/bin'
a,b=vir.split('=')
print('a={}'.format(a))
print('b={}'.format(b))
a=JAVA_HOME
b=/usr/bin
原文地址:https://www.cnblogs.com/omgasw/p/11776066.html