美文网首页
Python自学草稿(1)

Python自学草稿(1)

作者: 施小炜 | 来源:发表于2016-07-17 14:48 被阅读0次

    本篇不具备可读性,慎点。

    ▍Primitive Datatypes & Operators

    #判断变量b与变量a的值是否相同

    b is a

    #阶乘

    2**4

    #字符串的两种写法

    "string"  'string'

    #String组合的方式

    "Hello" + "World!"

    "Hello" "World!"

    #String 索引到Character

    "This is a string"[0]      #'T'

    #String 中可以加入format

    "{} can be {}".format("Strings", "interpolated")    # "Strings can be interpolated"

    #String中format多样的使用方法

    "{0} is funny, and {0} is {1}".format("He", "cute")    #"He is funny, and he is cute"

    "{name} wants to be {adj}".format(name="Wallace", adj="cool")    #Wallace wants to be cool

    ▍Variables and Collections

    #print的不同用法

    print("I'm Python, Nice to meet you!")

    print("I'm Python, Nice to meet you", end="!")

    #读取命令行中输入的数据的方法

    input_string_var = input("Enter some data: ")

    #赋予变量值,无需事先声明变量的类型

    some_var = 5

    #if的用法

    "yahoo!" if 3>2 else 2

    #list的操作方式

    li = []

    li.append(1)    #now li is [1]

    li.append(2)    #now li is [1,2]

    li.pop()    #now li is [1]

    li.append(3)    #now li is [1,3]

    li[0]    #->1

    li[-1]    #->3 the last one

    li = [1,2,3,5]

    other_li = [4,5,6]

    li[1:3]    #It's a closed/open range, so ->[2,3]

    li[1:]    #->[2,3,5]

    li[:3]    #->[1,2,3]

    li[::2]    #->[1,3] select every second entry

    li[::-1]    #->[5,3,2,1] return a reversed copy of the list

    li2 = li[:]    #get a copy

    del li[2]    # li is now [1,2,5]

    li.remove(2)    # li is now [1,5]

    li.insert(1,2)    # 第一个变量指position,第二变量是插入的值 li is  [1,2,5]

    li.index(2)    #2在li中的位置,-》1

    li.extend(other_li)     #now li is [1,2,5,4,5,6]

    1 in li    #true

    len(li)    #6

    #tup数组

    tup = (1,2,3)

    tup[0]    #->1

    type((1))    #

    type((1,))    #

    type(())    #

    len(tup)    #->3

    tup + (4,5,6)    #->(1,2,3,4,5,6)

    2 in tup    #->True

    a,b,c = (1,2,3)    #a=1, b=2, c=3

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

    a,b = b,a #easy to swap two values

    #Dictionaries ##immutable types: ints, floats, strings, tuples

    empty_dict = {}

    filled_dict = {"one":1, "two":2, "three":3}

    valid_dict = {(1,2,3):[1,2,3]}

    list(filled_dict.keys())    #->["three", "two", "one"]

    list(filled_dict.values())    #->[3,2,1]

    filled_dict.get("one")    #->1

    filled_dict.get("one",4)    #->1

    filled_dict.get("four", 4)    #->4

    filled_dict.setdefault("five", 5)    #filled_dict["five"] is set to 5

    filled_dict.setdefault("five", 6)    #由于缺省值已经有了,故依然为5

    filled_dict.update({"four":4})

    del filled_dict["one"]

    #Sets集合

    empty_set = set{}

    some_set = {1,1,2,3,4,5}    #some_set is now {1,2,3,4,5}

    filled_set = some_set

    filled_set.add(6)

    other_set = {3,4,5,6,7}

    filled_set & other_set    #->{3,4,5,6}     #与,获取交集

    filled_set | other_set    #->{1,2,3,4,5,6,7}    #或,获取并集

    filled_set - other_set    #->{1,2}

    filled_set ^ other_set    #->{1,2,6,7}

    {1,2} <= {1,2,3}    #True,表示子集

    ▍Control Flow and Iterables

    some_var = 5

    #判断流

    if some_var >10:

    print("a is bigger than 10")

    eif some_var < 10:

    print("a is smaller than 10")

    else:

    print("a is indeed 10")

    #循环流

    for animal in ["dog", "cat", "mouse"]

    print("{} is a mammal".format(animal))

    #输出结果

    #dog is a mammal

    #cat is a mammal

    #mouse is a mammal

    for i in range(4)

    print(i)

    """

    prints:

    0

    1

    2

    3

    """

    for i in range(4,8)

    print(i)

    """

    prints:

    4

    5

    6

    7

    """

    for i in range(4,8,2)

    print(i)

    """

    prints:

    4

    6

    """

    #循环流 while 循环

    x=0

    while x<4:

    print(x)

    #错误抛出

    try:

    raise IndexError("This is an Index Erro")

    except IndexError as e:

    pass

    except (TypeError, NameError)

    pass

    else:

    print("All Good!")

    finally:

    print("We can clean up resources here")

    #with 语句,不会有异常抛出

    with open("myfile.txt") as f:

    for line in f:

    print(line)

    #iterable -> Sequence

    our_iterator = iter(["one","two","three"])

    next(our_iterator)    #->"one"

    next(our_iterator)    #->"two"

    next(our_iterator)    #->"three"

    ▍Functions

    #函数add

    def add(x,y):

    return x+y

    add(5,6)    #11

    #函数var-args

    def varargs(*args)

    return args

    varargs(1,2,3)    #(1,2,3)

    #函数keywords

    def keyword_args(**args)

    return keyword_args

    keyword_args(big="foot",loch="ness")    #{"big":"foot", "loch":"ness"}

    #函数范围

    x=5

    def  set_x(num)

    x=num

    print(x)

    set_x(6)    #x==5

    def set_global_x(num)

    global x

    x=num

    print(x)

    set_global_x    #x==6

    #函数速写

    f=lambda x:x>2

    f(3)    #True

    #上述例子也可以改为

    (lambda x:x>2)(3)

    #map函数会根据提供的函数对指定序列作映射

    list(map(add_10, [1,2,3]))    #[11,12,13]

    list(map(max, [1,2,3], [4,5,2]))    #[4,5,3]

    #filter函数会对指定序列执行过滤操作

    list(filter(lambda x:x>5, [3,4,5,6,7]))

    #List comprehension

    [add10(i) for i in [1,2,3]]

    ▍Classes

    class Human:

    species = "H. sapiens"

    def __int__(self, name):

    self.name = name

    self.age=0

    ▍Models

    import math

    print(math.sqrt(16))

    from math import ceil, floor

    print(ceil(3.7))    #不需要使用math.XX

    print(floor(3.7)

    import math as m

    #再度使用之前的例子

    print(m.sqrt(16))

    from math import *    #improt所有的函数

    ▍Advanced

    yield 相当于 return,不同的是它返回的是生成器  #可使用next()

    ▍Python使用特点

    --用缩进    ​代替大小括号    ​#缩进的空格号要尽量多

    相关文章

      网友评论

          本文标题:Python自学草稿(1)

          本文链接:https://www.haomeiwen.com/subject/tcdmqttx.html