In [6]:
#dir给出了方法的名称
s=""
print(dir(s))


['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

列表解析


In [9]:
col = [i for i in range(10)]
print(col)


[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In [11]:
col = [i for i in range(10) if i%2==0]
print(col)


[0, 2, 4, 6, 8]

In [13]:
{x:ord(x) for x in "abc"}  #字典解析


Out[13]:
{'a': 97, 'b': 98, 'c': 99}

In [14]:
10/5


Out[14]:
2.0

In [15]:
10//5  #floor除  省略小数点


Out[15]:
2

In [17]:
10/4.0


Out[17]:
2.5

In [18]:
10//4.0


Out[18]:
2.0

In [23]:
#floor和截断(trunc)
import math
print(math.floor(-2.5))  #四舍五入
print(math.trunc(-2.5))  #直接截断


-3
-2

In [1]:
#共享引用
l1 = 10
l2 = l1
l1 = 20
print(l2)


10

In [7]:
import sys
sys.getrefcount(l1)  #获取引用次数


Out[7]:
659

In [20]:
#python中是引用赋值,而不是简单的copy
l1 = [1,2,3]
l2 = l1
l2[0] = 3
print(l1)

#另一个例子,在下面这种情况下依然是引用,这点一定要多加注意
l1 = [1,2,3]
l2 = [1,2,l1]
l1[0]=10
print(l2)


[3, 2, 3]
[1, 2, [10, 2, 3]]

In [9]:
#关于== 和 is
# == 是判断值是否相等
# is 是判断是否相同对象,或者是否在同一个内存中

l1 = [1,2]
l2 = [1,2,3]
print(l1 is l2)

l1 = [1,2]
l2 = l1
print(l2 is l1)


False
True

In [11]:
#嵌套比较,按照顺寻比较
l1 = [(1,2),2]
l2 = [(1,2),3]
print(l1>l2)


False

In [15]:
print(None == True)
print([None,None] == True) #尽管有对象存在,依然表示False


False
False

In [18]:
#类型判断的两种方法
if type([1,2])==list:
    print(True)
    
    
print(isinstance([1,2],list))


True
True

In [30]:
#关于赋值语句
a,b = 10,11
print(a,b)

a,b = range(2)
print(a,b)


10 11
0 1

In [33]:
a,b="cd"
print(a,b)

#可以使用*号来进行统配
a,*b = "string"
print(a,b)


c d
s ['t', 'r', 'i', 'n', 'g']

In [29]:
((a,b),c)=("st","abc")
print(a,b,c)


s t abc

In [31]:
#巧妙的赋值循环
L=[1,2,3,4,5]
while L:
    front,L = L[0],L[1:]
    print(front,L)


1 [2, 3, 4, 5]
2 [3, 4, 5]
3 [4, 5]
4 [5]
5 []

In [4]:
###关于反斜线续行,使用反斜线将没写完的续上,
if 1==1 and  \
    2==2:
        print("a")


a

In [6]:
#或者使用()来续行
if (1==1 and 2
   ==2):
    print("a")


a

In [9]:
#将代码写在一行,需要用 ; 号隔开
x = 1 ; print(x)


1

In [24]:
#python中的真值判断有些不同,python中返回真或者假而不是True或者False
print(1 and 0)   #0代表假 所以返回0
print(1 and -2)  #非0代表真所以就随意返回一个值,由于and需要计算最后一个数,所以一般返回后面哪个值
print({} and []) #{} 和 []都是假,所以计算了第一个值发现是假就返回第一个值,无需计算第二个


0
-2
{}

In [ ]:
#小技巧,利用bool返回值来进行列表元素选择
A = [1,2][bool(2)]  #bool(2)返回True代表1,所以取出A[1]
print(A)

In [ ]:
#列表循环的小技巧
x = 'abcd'
while x:
    print(x[0])
    x = x[1:]

In [ ]:
#break会中断所处的那个while,不会中断最外层的while语句
x = "abcd"
while x:
    while x:
        if x[0] == 'b':
            break;
        print(x[0])
        x = x[1:]

In [2]:
#python中有while..else..语句,当while执行完之后,会执行else语句
x = [1,2,3]
while x:
    print(x[0])
    x = x[1:]
else:
    print("stop")


1
2
3
stop

In [7]:
#关于for 
#for语句中代码可以直接写在后面
for i in [1,2,3]:print(i)


1
2
3

In [8]:
#使用range
for i in range(3):print(i)


0
1
2

In [9]:
for i in range(-1,2):print(i)


-1
0
1

In [11]:
for i in range(0,10,2):print(i,end=" ")


0 2 4 6 8 

In [15]:
#zip 和 map 遍历
l1 = [1,2,3,4]
l2 = [6,7,8,9]
for (x,y) in zip(l1,l2):print(x,y,end="    ")


1 6    2 7    3 8    4 9    

In [17]:
#以最短的为准,进行遍历
l1 = "abcd"
l2 = "rst"
l3 = "efghigk"
for i in zip(l1,l2,l3):print(i)


('a', 'r', 'e')
('b', 's', 'f')
('c', 't', 'g')

In [25]:
#zip可以用来构造字典
dict(zip([1,2,3],"abc"))


Out[25]:
{1: 'a', 2: 'b', 3: 'c'}

In [24]:
#map是一个函数应用器
print(list(map(ord,"aaa")))


[97, 97, 97]

In [28]:
#enumerate使用,enumerate会返回元素的下标和这个元素值
for i in enumerate([1,2,3]):print(i)


(0, 1)
(1, 2)
(2, 3)

迭代


In [4]:
#手工迭代
l = [1,2,3,4]
L = iter(l)
print(L.__next__())


1

In [11]:
#map迭代
M = map(abs,(-1,-2))
print(next(M))


1

文档


In [12]:
##__doc__用法,下面是一个文件假设名为:test.py

"""
This is introduction
"""

def abc():
    """
    This is function
    """
    print("hello")

In [13]:
#引用函数时,会返回函数说明
print(abc.__doc__)


    This is function
    

In [ ]:
## 引用文件时,会返回文件开头说明
import test
print(test.__doc__)
result
    this is introduction

In [14]:
class EE:
    "this is a class"
    pass
print(EE.__doc__)  #返回函数说明


this is a class

In [16]:
## 可以通过__doc__读取官方函数说明
import math
print(math.__doc__)


This module is always available.  It provides access to the
mathematical functions defined by the C standard.

In [17]:
print(math.sqrt.__doc__)


sqrt(x)

Return the square root of x.

In [22]:
#使用help可以读取这个模块中所有函数以及类的说明
help(math)


Help on built-in module math:

NAME
    math

DESCRIPTION
    This module is always available.  It provides access to the
    mathematical functions defined by the C standard.

FUNCTIONS
    acos(...)
        acos(x)
        
        Return the arc cosine (measured in radians) of x.
    
    acosh(...)
        acosh(x)
        
        Return the inverse hyperbolic cosine of x.
    
    asin(...)
        asin(x)
        
        Return the arc sine (measured in radians) of x.
    
    asinh(...)
        asinh(x)
        
        Return the inverse hyperbolic sine of x.
    
    atan(...)
        atan(x)
        
        Return the arc tangent (measured in radians) of x.
    
    atan2(...)
        atan2(y, x)
        
        Return the arc tangent (measured in radians) of y/x.
        Unlike atan(y/x), the signs of both x and y are considered.
    
    atanh(...)
        atanh(x)
        
        Return the inverse hyperbolic tangent of x.
    
    ceil(...)
        ceil(x)
        
        Return the ceiling of x as an Integral.
        This is the smallest integer >= x.
    
    copysign(...)
        copysign(x, y)
        
        Return a float with the magnitude (absolute value) of x but the sign 
        of y. On platforms that support signed zeros, copysign(1.0, -0.0) 
        returns -1.0.
    
    cos(...)
        cos(x)
        
        Return the cosine of x (measured in radians).
    
    cosh(...)
        cosh(x)
        
        Return the hyperbolic cosine of x.
    
    degrees(...)
        degrees(x)
        
        Convert angle x from radians to degrees.
    
    erf(...)
        erf(x)
        
        Error function at x.
    
    erfc(...)
        erfc(x)
        
        Complementary error function at x.
    
    exp(...)
        exp(x)
        
        Return e raised to the power of x.
    
    expm1(...)
        expm1(x)
        
        Return exp(x)-1.
        This function avoids the loss of precision involved in the direct evaluation of exp(x)-1 for small x.
    
    fabs(...)
        fabs(x)
        
        Return the absolute value of the float x.
    
    factorial(...)
        factorial(x) -> Integral
        
        Find x!. Raise a ValueError if x is negative or non-integral.
    
    floor(...)
        floor(x)
        
        Return the floor of x as an Integral.
        This is the largest integer <= x.
    
    fmod(...)
        fmod(x, y)
        
        Return fmod(x, y), according to platform C.  x % y may differ.
    
    frexp(...)
        frexp(x)
        
        Return the mantissa and exponent of x, as pair (m, e).
        m is a float and e is an int, such that x = m * 2.**e.
        If x is 0, m and e are both 0.  Else 0.5 <= abs(m) < 1.0.
    
    fsum(...)
        fsum(iterable)
        
        Return an accurate floating point sum of values in the iterable.
        Assumes IEEE-754 floating point arithmetic.
    
    gamma(...)
        gamma(x)
        
        Gamma function at x.
    
    gcd(...)
        gcd(x, y) -> int
        greatest common divisor of x and y
    
    hypot(...)
        hypot(x, y)
        
        Return the Euclidean distance, sqrt(x*x + y*y).
    
    isclose(...)
        isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0) -> bool
        
        Determine whether two floating point numbers are close in value.
        
           rel_tol
               maximum difference for being considered "close", relative to the
               magnitude of the input values
            abs_tol
               maximum difference for being considered "close", regardless of the
               magnitude of the input values
        
        Return True if a is close in value to b, and False otherwise.
        
        For the values to be considered close, the difference between them
        must be smaller than at least one of the tolerances.
        
        -inf, inf and NaN behave similarly to the IEEE 754 Standard.  That
        is, NaN is not close to anything, even itself.  inf and -inf are
        only close to themselves.
    
    isfinite(...)
        isfinite(x) -> bool
        
        Return True if x is neither an infinity nor a NaN, and False otherwise.
    
    isinf(...)
        isinf(x) -> bool
        
        Return True if x is a positive or negative infinity, and False otherwise.
    
    isnan(...)
        isnan(x) -> bool
        
        Return True if x is a NaN (not a number), and False otherwise.
    
    ldexp(...)
        ldexp(x, i)
        
        Return x * (2**i).
    
    lgamma(...)
        lgamma(x)
        
        Natural logarithm of absolute value of Gamma function at x.
    
    log(...)
        log(x[, base])
        
        Return the logarithm of x to the given base.
        If the base not specified, returns the natural logarithm (base e) of x.
    
    log10(...)
        log10(x)
        
        Return the base 10 logarithm of x.
    
    log1p(...)
        log1p(x)
        
        Return the natural logarithm of 1+x (base e).
        The result is computed in a way which is accurate for x near zero.
    
    log2(...)
        log2(x)
        
        Return the base 2 logarithm of x.
    
    modf(...)
        modf(x)
        
        Return the fractional and integer parts of x.  Both results carry the sign
        of x and are floats.
    
    pow(...)
        pow(x, y)
        
        Return x**y (x to the power of y).
    
    radians(...)
        radians(x)
        
        Convert angle x from degrees to radians.
    
    sin(...)
        sin(x)
        
        Return the sine of x (measured in radians).
    
    sinh(...)
        sinh(x)
        
        Return the hyperbolic sine of x.
    
    sqrt(...)
        sqrt(x)
        
        Return the square root of x.
    
    tan(...)
        tan(x)
        
        Return the tangent of x (measured in radians).
    
    tanh(...)
        tanh(x)
        
        Return the hyperbolic tangent of x.
    
    trunc(...)
        trunc(x:Real) -> Integral
        
        Truncates x to the nearest Integral toward 0. Uses the __trunc__ magic method.

DATA
    e = 2.718281828459045
    inf = inf
    nan = nan
    pi = 3.141592653589793

FILE
    (built-in)



In [ ]:


In [ ]: