• PythonDay01


    》注释

      》》当行注视:# 被注释内容

      》》多行注释:""" 被注释内容 """

    》执行脚本传入参数

      》》Python有大量的模块,从而使得开发Python程序非常简洁。类库有包括三中:

        》》》Python内部提供的模块

        》》》业内开源的模块

        》》》程序员自己开发的模块

      》》Python内部提供一个 sys 的模块,其中的 sys.argv 用来捕获执行执行python脚本时传入的参数

    import sys
    
    print(sys.argv)
    

    》pyc 文件

      》》执行Python代码时,如果导入了其他的 .py 文件,那么,执行过程中会自动生成一个与其同名的 .pyc 文件,该文件就是Python解释器编译之后产生的字节码。

      》》ps:代码经过编译可以产生字节码;字节码通过反编译也可以得到代码。

      》》python语言的执行:代码编译得到字节码虚拟机执行字节码并转换成机器码再后在处理器上执行

    》变量

      》》声明一个变量,变量名为: name,变量name的值为:"fury"

    name = "fury"
    

      》》 变量的作用:昵称,其代指内存里某个地址中保存的内容

      》》变量定义的规则:

        》》》变量名只能是 字母、数字或下划线的任意组合

        》》》变量名的第一个字符不能是数字

        》》》以下关键字不能声明为变量名

          ['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']

    》变量的赋值

      》》Python中变量的赋值同Java中字符串的操作差不多(详见Java字符串操作之常量池)

    name1 = 'fury'
    name2 = 'fury' #同一个字符串可以被不同的变量引用  #name2 = name1 也是同样的效果
    id1 = id(name1) #通过内置函数id()来读取变量的内存地址
    id2 = id(name2)
    print(id1, id2)
    name2 = "warrior" #改变name2的值时name2的地址也变了,但是name1的值和地址都没有变
    print(name1, name2)
    id1 = id(name1) #通过内置函数id()来读取变量的内存地址
    id2 = id(name2)
    print(id1, id2)
    # PS: Python中字符串的赋值操作跟Java中的差不多
    
    # x1 = 2
    # x2 = x1
    # id1 = id(x1)
    # id2 = id(x2)
    # print(x1, x2)
    # print(id1, id2)
    #
    # x2 = 12343
    # print(x1, x2)
    # id1 = id(x1)
    # id2 = id(x2)
    # print(id1, id2)
    

    》补充

      》#print "hello"            python2.x的print方法

      》#python2.x不支持中文,如果有中文,需要添加 #_*_coding:utf-8_*_

      在程序最开始指定解释器和编码规则

    #!/usr/bin/env python
    # _*_coding:utf-8_*_

    》输入

      在3.0中input输入的默认都是字符串形式

    name = input("Please input your name: ")
    print(name)
    # print(input("Please input your name: "))  #上面两行的优化版本
    # 在3.0中input输入的默认都是字符串形式
    
    name = input("Please input your name: ")
    age = int(input("Please input your age: "))  #convet string to int
    salary = float(input("Please input your salary: "))
    print("name:", name)
    print("age:", age)
    print("slary", salary)
    
    msg = """
    =====start=====
    Information of %s :
    name : %s
    age : %d
    salary : %f
    ======end=======
    """ %(name, name, age, salary)
    print(msg)
    

    》流程控制和缩进

      》》需求一:   

      # 提示输入用户名和密码
      # 验证用户名和密码
      # 如果错误,则输出用户名或密码错误
      # 如果成功,则输出 欢迎,XXX!
    name = input("Please input your name: ")
    passwords = input("Please input your passwords: ")
    if name == "fury" and  passwords == 123:
            print("登录成功")
    else:
        print("用户名或者密码错误")
    

      》》需求二

        根据用户输入内容输出其权限

    name = input("Please input your name: ")
    passwords = input("Please input your passwords: ")
    index = input("Please input you ID: ")
    if index.isdigit():
        index = int(index)
    if passwords.isdigit():
        passwords = int(passwords)
    if name == "fury" and  passwords == 123:
            print("登录成功")
            if index == 1:
                print("你是博士")
            elif index == 2:
                print("你是硕士")
            elif index == 3:
                print("你是本科生")
            else:
                print("你是中学生")
    else:
        print("用户名或者密码错误")
    

    》局部变量 VS 全局变量

      外层变量,可以被内层变量使用
      内层变量,无法被外层变量使用
      》》当局部变量和全局变量冲突时,以局部变量为准
     1 name = "fury"
     2 
     3 
     4 def test():
     5     name = "warrior"
     6     print("test函数:", name)
     7 
     8 
     9 def main():
    10     test()
    11     print("main函数", name)
    12 
    13 main()
    View Code

      》》当想要在局部对全局变量进行修改是需要用到 global 关键字

     1 name = "fury"
     2 
     3 
     4 def test():
     5     global name
     6     name = "hello word"
     7     print("test函数:", name)
     8 
     9 
    10 def main():
    11     test()
    12     print("main函数", name)
    13 
    14 main()
    View Code

    》初识基本数据类型

    1、数字

    2 是一个整数的例子。
    长整数 不过是大一些的整数。
    3.23和52.3E-4是浮点数的例子。E标记表示10的幂。在这里,52.3E-4表示52.3 * 10-4。
    (-5+4j)和(2.3-4.6j)是复数的例子。

    int(整型)

      在32位机器上,整数的位数为32位,取值范围为-2**31~2**31-1,即-2147483648~2147483647
      在64位系统上,整数的位数为64位,取值范围为-2**63~2**63-1,即-9223372036854775808~9223372036854775807
      1 class int(object):
      2     """
      3     int(x=0) -> int or long
      4     int(x, base=10) -> int or long
      5     
      6     Convert a number or string to an integer, or return 0 if no arguments
      7     are given.  If x is floating point, the conversion truncates towards zero.
      8     If x is outside the integer range, the function returns a long instead.
      9     
     10     If x is not a number or if base is given, then x must be a string or
     11     Unicode object representing an integer literal in the given base.  The
     12     literal can be preceded by '+' or '-' and be surrounded by whitespace.
     13     The base defaults to 10.  Valid bases are 0 and 2-36.  Base 0 means to
     14     interpret the base from the string as an integer literal.
     15     >>> int('0b100', base=0)
     16     """
     17     def bit_length(self): 
     18         """ 返回表示该数字的时占用的最少位数 """
     19         """
     20         int.bit_length() -> int
     21         
     22         Number of bits necessary to represent self in binary.
     23         >>> bin(37)
     24         '0b100101'
     25         >>> (37).bit_length()
     26         """
     27         return 0
     28 
     29     def conjugate(self, *args, **kwargs): # real signature unknown
     30         """ 返回该复数的共轭复数 """
     31         """ Returns self, the complex conjugate of any int. """
     32         pass
     33     #两个实部相等,虚部互为相反数的复数互为共轭复数(conjugate #complex number)
     34     def __abs__(self):
     35         """ 返回绝对值 """
     36         """ x.__abs__() <==> abs(x) """
     37         pass
     38 
     39     def __add__(self, y):
     40         """ x.__add__(y) <==> x+y """
     41         pass
     42 
     43     def __and__(self, y):
     44         """ x.__and__(y) <==> x&y """
     45         pass
     46 
     47     def __cmp__(self, y): 
     48         """ 比较两个数大小 """
     49         """ x.__cmp__(y) <==> cmp(x,y) """
     50         pass
     51 
     52     def __coerce__(self, y):
     53         """ 强制生成一个元组 """ 
     54         """ x.__coerce__(y) <==> coerce(x, y) """
     55         pass
     56 
     57     def __divmod__(self, y): 
     58         """ 相除,得到商和余数组成的元组 """ 
     59         """ x.__divmod__(y) <==> divmod(x, y) """
     60         pass
     61 
     62     def __div__(self, y): 
     63         """ x.__div__(y) <==> x/y """
     64         pass
     65 
     66     def __float__(self): 
     67         """ 转换为浮点类型 """ 
     68         """ x.__float__() <==> float(x) """
     69         pass
     70 
     71     def __floordiv__(self, y): 
     72         """ x.__floordiv__(y) <==> x//y """
     73         pass
     74 
     75     def __format__(self, *args, **kwargs): # real signature unknown
     76         pass
     77 
     78     def __getattribute__(self, name): 
     79         """ x.__getattribute__('name') <==> x.name """
     80         pass
     81 
     82     def __getnewargs__(self, *args, **kwargs): # real signature unknown
     83         """ 内部调用 __new__方法或创建对象时传入参数使用 """ 
     84         pass
     85 
     86     def __hash__(self): 
     87         """如果对象object为哈希表类型,返回对象object的哈希值。哈希值为整数。在字典查找中,哈希值用于快速比较字典的键。两个数值如果相等,则哈希值也相等。"""
     88         """ x.__hash__() <==> hash(x) """
     89         pass
     90 
     91     def __hex__(self): 
     92         """ 返回当前数的 十六进制 表示 """ 
     93         """ x.__hex__() <==> hex(x) """
     94         pass
     95 
     96     def __index__(self): 
     97         """ 用于切片,数字无意义 """
     98         """ x[y:z] <==> x[y.__index__():z.__index__()] """
     99         pass
    100 
    101     def __init__(self, x, base=10): # known special case of int.__init__
    102         """ 构造方法,执行 x = 123 或 x = int(10) 时,自动调用,暂时忽略 """ 
    103         """
    104         int(x=0) -> int or long
    105         int(x, base=10) -> int or long
    106         
    107         Convert a number or string to an integer, or return 0 if no arguments
    108         are given.  If x is floating point, the conversion truncates towards zero.
    109         If x is outside the integer range, the function returns a long instead.
    110         
    111         If x is not a number or if base is given, then x must be a string or
    112         Unicode object representing an integer literal in the given base.  The
    113         literal can be preceded by '+' or '-' and be surrounded by whitespace.
    114         The base defaults to 10.  Valid bases are 0 and 2-36.  Base 0 means to
    115         interpret the base from the string as an integer literal.
    116         >>> int('0b100', base=0)
    117         # (copied from class doc)
    118         """
    119         pass
    120 
    121     def __int__(self): 
    122         """ 转换为整数 """ 
    123         """ x.__int__() <==> int(x) """
    124         pass
    125 
    126     def __invert__(self): 
    127         """ x.__invert__() <==> ~x """
    128         pass
    129 
    130     def __long__(self): 
    131         """ 转换为长整数 """ 
    132         """ x.__long__() <==> long(x) """
    133         pass
    134 
    135     def __lshift__(self, y): 
    136         """ x.__lshift__(y) <==> x<<y """
    137         pass
    138 
    139     def __mod__(self, y): 
    140         """ x.__mod__(y) <==> x%y """
    141         pass
    142 
    143     def __mul__(self, y): 
    144         """ x.__mul__(y) <==> x*y """
    145         pass
    146 
    147     def __neg__(self): 
    148         """ x.__neg__() <==> -x """
    149         pass
    150 
    151     @staticmethod # known case of __new__
    152     def __new__(S, *more): 
    153         """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
    154         pass
    155 
    156     def __nonzero__(self): 
    157         """ x.__nonzero__() <==> x != 0 """
    158         pass
    159 
    160     def __oct__(self): 
    161         """ 返回改值的 八进制 表示 """ 
    162         """ x.__oct__() <==> oct(x) """
    163         pass
    164 
    165     def __or__(self, y): 
    166         """ x.__or__(y) <==> x|y """
    167         pass
    168 
    169     def __pos__(self): 
    170         """ x.__pos__() <==> +x """
    171         pass
    172 
    173     def __pow__(self, y, z=None): 
    174         """ 幂,次方 """ 
    175         """ x.__pow__(y[, z]) <==> pow(x, y[, z]) """
    176         pass
    177 
    178     def __radd__(self, y): 
    179         """ x.__radd__(y) <==> y+x """
    180         pass
    181 
    182     def __rand__(self, y): 
    183         """ x.__rand__(y) <==> y&x """
    184         pass
    185 
    186     def __rdivmod__(self, y): 
    187         """ x.__rdivmod__(y) <==> divmod(y, x) """
    188         pass
    189 
    190     def __rdiv__(self, y): 
    191         """ x.__rdiv__(y) <==> y/x """
    192         pass
    193 
    194     def __repr__(self): 
    195         """转化为解释器可读取的形式 """
    196         """ x.__repr__() <==> repr(x) """
    197         pass
    198 
    199     def __str__(self): 
    200         """转换为人阅读的形式,如果没有适于人阅读的解释形式的话,则返回解释器课阅读的形式"""
    201         """ x.__str__() <==> str(x) """
    202         pass
    203 
    204     def __rfloordiv__(self, y): 
    205         """ x.__rfloordiv__(y) <==> y//x """
    206         pass
    207 
    208     def __rlshift__(self, y): 
    209         """ x.__rlshift__(y) <==> y<<x """
    210         pass
    211 
    212     def __rmod__(self, y): 
    213         """ x.__rmod__(y) <==> y%x """
    214         pass
    215 
    216     def __rmul__(self, y): 
    217         """ x.__rmul__(y) <==> y*x """
    218         pass
    219 
    220     def __ror__(self, y): 
    221         """ x.__ror__(y) <==> y|x """
    222         pass
    223 
    224     def __rpow__(self, x, z=None): 
    225         """ y.__rpow__(x[, z]) <==> pow(x, y[, z]) """
    226         pass
    227 
    228     def __rrshift__(self, y): 
    229         """ x.__rrshift__(y) <==> y>>x """
    230         pass
    231 
    232     def __rshift__(self, y): 
    233         """ x.__rshift__(y) <==> x>>y """
    234         pass
    235 
    236     def __rsub__(self, y): 
    237         """ x.__rsub__(y) <==> y-x """
    238         pass
    239 
    240     def __rtruediv__(self, y): 
    241         """ x.__rtruediv__(y) <==> y/x """
    242         pass
    243 
    244     def __rxor__(self, y): 
    245         """ x.__rxor__(y) <==> y^x """
    246         pass
    247 
    248     def __sub__(self, y): 
    249         """ x.__sub__(y) <==> x-y """
    250         pass
    251 
    252     def __truediv__(self, y): 
    253         """ x.__truediv__(y) <==> x/y """
    254         pass
    255 
    256     def __trunc__(self, *args, **kwargs): 
    257         """ 返回数值被截取为整形的值,在整形中无意义 """
    258         pass
    259 
    260     def __xor__(self, y): 
    261         """ x.__xor__(y) <==> x^y """
    262         pass
    263 
    264     denominator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    265     """ 分母 = 1 """
    266     """the denominator of a rational number in lowest terms"""
    267 
    268     imag = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    269     """ 虚数,无意义 """
    270     """the imaginary part of a complex number"""
    271 
    272     numerator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    273     """ 分子 = 数字大小 """
    274     """the numerator of a rational number in lowest terms"""
    275 
    276     real = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    277     """ 实属,无意义 """
    278     """the real part of a complex number"""
    279 
    280 int
    View Code
    long(长整型)
      跟C语言不同,Python的长整数没有指定位宽,即:Python没有限制长整数数值的大小,但实际上由于机器内存有限,我们使用的长整数数值不可能无限大。
      注意,自从Python2.2起,如果整数发生溢出,Python会自动将整数数据转换为长整数,所以如今在长整数数据后面不加字母L也不会导致严重后果了。
    float(浮点型)
      浮点数用来处理实数,即带有小数的数字。类似于C语言中的double类型,占8个字节(64位),其中52位表示底,11位表示指数,剩下的一位表示符号。
    complex(复数)
      复数由实数部分和虚数部分组成,一般形式为x+yj,其中的x是复数的实数部分,y是复数的虚数部分,这里的x和y都是实数。
    注:Python中存在小数字池:-5 ~ 257
     
    2、布尔值
      真或假
      1 或 0
    3、字符串
    "hello world"

      》》万恶的字符串拼接:

      python中的字符串在C语言中体现为是一个字符数组,每次创建字符串时候需要在内存中开辟一块连续的空,并且一旦需要修改字符串的话,就需要再次开辟空间,万恶的+号每出现一次就会在内从中重新开辟一块空间。(PS:同Java的字符串拼接相同)
    1 name = "fury"
    2 age = 23
    3 print("The age of that fellow named %s is %d" %(name, age))
    4 print("The age of that fellow named {0} is {1}".format(*[name, age]))
    5 print("The age of that fellow named {name} is {age}".format(**{"name" : "warrior","age" : 123}))
    View Code
    # Keep Calm and Carry on
    # _*_coding:utf-8_*_
    # Author: NeverCtrl_C
    """
    """
    # strip() 方法会去掉字符串前后的空格、tab键、换行等等
    print("===start===")
    # userName = input("Please input your name: ")
    # if userName.strip() == "fury":
    #     print("Welcome to the city of Chongqing! ")
    #将字符串切成列表
    print("===one===")
    name = "One,Two,Three"
    name1 = name.split(",")
    print(name1)
    # 将列表合成一个字符串
    print("===two===")
    name2 = "|".join(name1)
    print(name2)
    # 判断一个字符串里面有没有空格
    print("===three===")
    name3 = "fury wArrior"
    print(" " in name3)
    # 将字符串的首字母大写,其余的全部小写
    print("===four===")
    print(name3.capitalize())
    View Code
    # Keep Calm and Carry on
    # _*_coding:utf-8_*_
    # Author: NeverCtrl_C
    """
    """
    # 字符串的格式
    print("===start===")
    msg = "Hello, {name}. Your age is {age}."
    print(msg.format(name = "fury", age = 123))
    
    msg1 = "Hello, {0}. Your age is {1}."
    print(msg1.format("warrior",321))
    # 切片
    print("===one===")
    name = "Thinking in Java"
    print(name[0:8])
    # len()  字符串长度
    print("===two===")
    print(len(name))
    # center() 将字符串放在自定宽度的中间,多余的位置用指定的字符进行填充
    print("===three===")
    print(name.center(20,"-"))
    print(name.center(len(name) + 6,"&"))
    # find()  做出指定字符串的索引
    print("===four===")
    print(name.find("T"))
    print(name.find("1234"))  #没有返回 -1
    # 判断输入的是否是数字
    print("===five===")
    age = input("Please input your age: ")
    if age.isdigit():
        age = int(age)
    else:
        print("Invalid input")
    print("===six===")
    name1 = "furywarrior"
    print(name1.endswith("warrior"))  # 结束判断
    print(name1.startswith("fury")) #开始判断
    print(name1.upper()) #全部转换成大写
    print(name1.lower()) #全部转换成小写
    View Code

    》列表

    Python 中的list 就相当于 Java 中的数组;但是Python中的list可以存储不同的数据类型
    # Keep Calm and Carry on
    # _*_coding:utf-8_*_
    # Author: NeverCtrl_C
    """
    """
    # Python 中的list 就相当于 Java 中的数组;但是Python中的list可以存储不同的数据类型
    name = ["fury", "warrior",1,2,3,4,"peter","bob"]
    print(name[1])
    print(name[-1])
    print(name[0:2]) #切片   注意:和Java一样,取首不取尾
    print(name[-5:-1]) #没取到最后一个 ,原因:取首不取尾
    print(name[-5:]) #不写后面这个参数,就默认取到最后一个并且包含最后一个
    print(name[0:6])
    print(name[:6])
    print(name[0:3])
    print(name[0:3][0:2])
    print(name[0:3][0:2][1])
    print("====")
    print(name[0:3][0:2][1][1])
    print("===")
    name2 = list(["warrior", "fury"])
    print(name2[0:1])
    # print(name2[0:1][1]) #切分到只有两个元素后,就不要再进行切分啦,直接利用下标进行引用
    print(name2[0][1])
    print("===start===")
    print(name2)
    print("===one===")
    name2[1] = "peter"  #修改元素的值
    print(name2)
    print("===two===")
    name2.insert(0,"bob") #插入一个元素到列表中
    print(name2)
    print("===three===")
    name2.append("hello")  #追加一个元素到最后
    print(name2)
    print("===four===")
    name2.remove("bob")  #删除一个元素
    print(name2)
    View Code
    # Keep Calm and Carry on
    # _*_coding:utf-8_*_
    # Author: NeverCtrl_C
    """
    """
    name = ["fury",'warrior',1234,3,234,3,1,234,23,3,"bob","fury"]
    if "fury" in name:  #判断"fury" 是否在列表name中
        num_of_ele = name.count("fury")  #算出"fury"在列表中的个数
        positionOfEle = name.index("fury") #找到第一个"fury"的位置
        print("[%d] "fury" is in the list of name and the first position is [%d]." %(num_of_ele, positionOfEle))
        print(name[positionOfEle])
        name[positionOfEle] = "peter"  #修改元素的值
        print(name[positionOfEle])
    print("===one===")
    #怎么改变一个列表中所有的相同元素
    
    name1 = list([1,2,3,4,4,2,1,2,1,2,1,1,1])
    print(name1)
    #同时改变相同元素的值
    if 1 in name1:
        numOf1 = name1.count(1)
        print("%d 1 is in the list of name1." %(numOf1))
        for i in range(numOf1):
            posOf1 = name1.index(1)
            name1[posOf1] = "33"
    
    print(name1)
    print(1 in name1)
    View Code
    # Keep Calm and Carry on
    # _*_coding:utf-8_*_
    # Author: NeverCtrl_C
    """
    """
    """
    作业要求:
        写一个列表,列表包含本组所有成员
        往中间插入两个临组成员的名字
        取出两个临组成员
        删除第12个人
        把刚才加入的那2个其它组的人一次性删除
        把组长的名字加上组长备注
        每隔一个人打印一个人
    """
    name2 = [5, 6, 7, 8]
    name1 = [1, 2, 3, 4]
    name3 = [9, 10, 11, 12]
    print("===start===")
    for i in range(8):
        if i < 4 :
            name2.insert(2 + i, name1[i])
        else:
            name2.insert(2 + i, name3[-(8 - i)])
    print(name2)
    print("===one===")
    name4 = name2[2:10] # 切片处理
    print(name4)
    print("===two===")
    name2.remove(8)  #删除一个元素
    print(name2)
    print("===three===")
    del name2[2:10]   # del 是全局的,什么都可以删  #删除多个元素
    print(name2)
    print("===four===")
    name2[0] = "组长"   #改变元素的值
    print(name2)
    print("===five===")
    print(name2[0::2])  #间隔打印列表的元素
    print("===six===")
    x = 123
    print(x)
    del x
    # print(x)  #经过del删除后变量x就不存在啦
    View Code
    # Keep Calm and Carry on
    # _*_coding:utf-8_*_
    # Author: NeverCtrl_C
    """
    """
    # 经一个列表整体加载到另一个列表的后面
    print("===start===")
    name1 = [1,2,3,12,321,32,21]
    name2 = [3,4,5]
    print(name1)
    name1.extend(name2)
    print(name1)
    print(name2)
    print("===one===")
    # 将一个列表进行反转处理
    name2.reverse()
    print(name2)
    # 排序:在3.5中不同的数据类型不能够混合排序
    name1.sort()
    print(name1)
    View Code
    # Keep Calm and Carry on
    # _*_coding:utf-8_*_
    # Author: NeverCtrl_C
    """
    """
    import copy
    # 利用pop删除元素
    print("===start===")
    name = ["fury","warrior","peter","bob"]
    print(name)
    name.pop()  #默认删除最后一个
    print(name)
    name.pop(1) #参数是元素的位置
    print(name)
    # copy方法_1
    print("===one===")
    name1 = ["fury","warrior","hello"]
    name2 = name1.copy()
    name1[0] = "FURY"
    print(name1)
    print(name2)
    # copy_2 : copy没有办法copy第二层,即如果列表中有一个元素是列表类型,那么copy过来的是
    #   这个列表的地址,而不是这个列表中真正的值,所以会形成一改全改的结果
    print("===two===")
    lis1 = ["fury","warrior",[1,2,3]]
    lis2 = lis1.copy()
    print(lis1)
    print(lis2)
    lis1[2][0] = "hello"
    print(lis1)
    print(lis2)
    lis2[2][1] = "world"
    print(lis1)
    print(lis2)
    #解决办法利用copy库
    print("===three===")
    lis3 = lis1.copy()
    print(lis3)
    # print("浅copy")
    # lis3 = copy.copy(lis1)
    # lis1[2][2] = "NeverCtrl_C"
    # print(lis3)
    print("深copy")
    lis3 = copy.deepcopy(lis1)
    lis1[2][2] = "NeverCtrl_C"
    print(lis3)
    View Code
    # Keep Calm and Carry on
    # _*_coding:utf-8_*_
    # Author: NeverCtrl_C
    """
    """
    # 找出所有的9并且改成999
    # 找出所有的34并且直接删掉
    lis = [9,1,34,2,9,23,34,9,9,34]
    print(lis.count(9))
    print(lis.count(34))
    print(lis)
    print("长度为:%d" %len(lis))
    for i in range(lis.count(9)):
        lis[lis.index(9)] = 999
    print(lis)
    for i in range(lis.count(34)):
        lis.remove(lis[lis.index(34)])
    print(lis)
    print("长度为:%d" %len(lis))
    View Code
    # Keep Calm and Carry on
    # _*_coding:utf-8_*_
    # Author: NeverCtrl_C
    """
    """
    list = ["fury","warrior","peter"]
    print("===one===")
    for item in enumerate(list):
        print(item)
    # enumerate() 是一个枚举,它返回的是一个元组,元组的第一个元素是
    # 从0开始的下标,元组的第二个元素是内容
    View Code
    # Keep Calm and Carry on
    # _*_coding:utf-8_*_
    # Author: NeverCtrl_C
    """
    """
    lis01 = [1,[1,2,"warrior"],("warrior",132),3,"fury"]
    print("33[41;1m%s33[0m" %lis01[1])
    # print("%s %s %s" %lis01[1])  # 错误的输出方法
    print("%s 33[31;1m%s33[0m" %lis01[2])
    # print("%s" %lis01[2]) # 错误写法
    
    #  在利用  print("%类型" %(变量)) 这种类型进行打印输出时,列表中的元素看成
    # 是一个整体,前提是列表中的元素不是元组类型的数据;如果是元组类型的数据,
    # 那么就必须根据该元组中元素的个数在“”里面添加相同数量的%数据类型个数
    
    # 033[31;1m%s033[0m   添加颜色
    View Code
    # Keep Calm and Carry on
    # _*_coding:utf-8_*_
    # Author: NeverCtrl_C
    """
    """
    """
    》购物小程序
        》》用户启动时先输入工资
        》》用户启动程序后打印商品列表
        》》允许用户选择购买商品
        》》允许用户不断的购买各种商品
        》》购买时检测余额是否足够,如果足够直接扣款,否则打印余额不足
        》》允许用户主动退出,退出时打印已购商品列表
    """
    salary = input("Please input your salary: ")
    if salary.isdigit():
        salary = int(salary)
    else :
        exit("Invalid data type ...")
    
    welcom_msg = "Welcome to ShoppingStore".center(50,"=")
    print(welcom_msg)
    products_list = [
        ("A" , 1000),
        ("B" , 2000),
        ("C" , 3000),
        ("D" , 4000),
        ("E" , 5000)
    ]
    shop_car = []
    
    # print(products_list[1][0],products_list[1][1])
    
    exit_flag = False
    while not exit_flag :
        for products_item in enumerate(products_list) :  #类似于Java中for循环的简便写法
            print(products_item)
        p_choice_index = input("[q:quit; c:check]What kind of products do you want to purchase?")
        if p_choice_index.isdigit():
            p_choice_index = int(p_choice_index)
            if p_choice_index < len(products_list):
                p_choice = products_list[p_choice_index]
                if salary >= p_choice[1]: #买得起
                    shop_car.append(p_choice) #加入购物车
                    salary -= p_choice[1] #减钱
                    print("The product you chose just now is [%s %d] " %(p_choice[0],p_choice[1]))
                    print("Your banance is 33[31;1m[%s]RMB33[0m " %salary)
                else:
                    for shop_item in enumerate(shop_car):
                        print(shop_item)
                    print("Your banance is [%s] , failling to affort ...." %salary)
        else:
            if p_choice_index == "q" or p_choice_index == "quit":
                print("You choose to quit.")
            else:
                print("Your input is wrong.")
    
            print("Purchaseed products as follow:".center(40,"="))
            for shop_item in shop_car:
                print(shop_item)
            print("Goodbye".center(40, "="))
            print("Your banance is [%s] " % salary)
            exit_flag = True
    
    """
    优化购物程序,购买时允     许用户购买多件商品
    允许多用户登录,下一次登录后,继续按上一次的余额继续购买(可以充值)
    允许用户查看之前的购买记录(记录要显示商品购买的时间)
    商品里列表分级展示
    """
    购物小程序

    》元组

      就是不能改变元素值得列表

    tup01 = (1,"fury",3)
    print(tup01, type(tup01))
    # tup01[0] = "fury"  #错误写法:元组的元素值不能够被更改
    元组
    tup01 = (1,"fury",3,1)
    print(tup01, type(tup01))
    # tup01[0] = "fury"  #错误写法:元组的元素值不能够被更改
    print(tup01.count(1))
    print(tup01.index("fury"))
    元组的方法
    lass tuple(object):
        """
        tuple() -> empty tuple
        tuple(iterable) -> tuple initialized from iterable's items
        
        If the argument is a tuple, the return value is the same object.
        """
        def count(self, value): # real signature unknown; restored from __doc__
            """ T.count(value) -> integer -- return number of occurrences of value """
            return 0
    
        def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
            """
            T.index(value, [start, [stop]]) -> integer -- return first index of value.
            Raises ValueError if the value is not present.
            """
            return 0
    
        def __add__(self, y): # real signature unknown; restored from __doc__
            """ x.__add__(y) <==> x+y """
            pass
    
        def __contains__(self, y): # real signature unknown; restored from __doc__
            """ x.__contains__(y) <==> y in x """
            pass
    
        def __eq__(self, y): # real signature unknown; restored from __doc__
            """ x.__eq__(y) <==> x==y """
            pass
    
        def __getattribute__(self, name): # real signature unknown; restored from __doc__
            """ x.__getattribute__('name') <==> x.name """
            pass
    
        def __getitem__(self, y): # real signature unknown; restored from __doc__
            """ x.__getitem__(y) <==> x[y] """
            pass
    
        def __getnewargs__(self, *args, **kwargs): # real signature unknown
            pass
    
        def __getslice__(self, i, j): # real signature unknown; restored from __doc__
            """
            x.__getslice__(i, j) <==> x[i:j]
                       
                       Use of negative indices is not supported.
            """
            pass
    
        def __ge__(self, y): # real signature unknown; restored from __doc__
            """ x.__ge__(y) <==> x>=y """
            pass
    
        def __gt__(self, y): # real signature unknown; restored from __doc__
            """ x.__gt__(y) <==> x>y """
            pass
    
        def __hash__(self): # real signature unknown; restored from __doc__
            """ x.__hash__() <==> hash(x) """
            pass
    
        def __init__(self, seq=()): # known special case of tuple.__init__
            """
            tuple() -> empty tuple
            tuple(iterable) -> tuple initialized from iterable's items
            
            If the argument is a tuple, the return value is the same object.
            # (copied from class doc)
            """
            pass
    
        def __iter__(self): # real signature unknown; restored from __doc__
            """ x.__iter__() <==> iter(x) """
            pass
    
        def __len__(self): # real signature unknown; restored from __doc__
            """ x.__len__() <==> len(x) """
            pass
    
        def __le__(self, y): # real signature unknown; restored from __doc__
            """ x.__le__(y) <==> x<=y """
            pass
    
        def __lt__(self, y): # real signature unknown; restored from __doc__
            """ x.__lt__(y) <==> x<y """
            pass
    
        def __mul__(self, n): # real signature unknown; restored from __doc__
            """ x.__mul__(n) <==> x*n """
            pass
    
        @staticmethod # known case of __new__
        def __new__(S, *more): # real signature unknown; restored from __doc__
            """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
            pass
    
        def __ne__(self, y): # real signature unknown; restored from __doc__
            """ x.__ne__(y) <==> x!=y """
            pass
    
        def __repr__(self): # real signature unknown; restored from __doc__
            """ x.__repr__() <==> repr(x) """
            pass
    
        def __rmul__(self, n): # real signature unknown; restored from __doc__
            """ x.__rmul__(n) <==> n*x """
            pass
    
        def __sizeof__(self): # real signature unknown; restored from __doc__
            """ T.__sizeof__() -- size of T in memory, in bytes """
            pass
    
    tuple
    list

    》字典

      字典是无序的,也是没有下标的

     1 # Keep Calm and Carry on
     2 # _*_coding:utf-8_*_
     3 # Author: NeverCtrl_C
     4 """
     5 """
     6 dic = {
     7     "name" : "fury",
     8     "age" : 123,
     9     "salary" : 15600
    10 
    11 }
    12 print(dic) # 打印整个字典
    13 print(dic["name"]) # 打印字典中指定关键字所对应的内容
    14 # 字典时没有下标的,故字典是无序的;所以打印字典的全部内容时是要变化的
    字典的创建和打印
    # Keep Calm and Carry on
    # _*_coding:utf-8_*_
    # Author: NeverCtrl_C
    """
    """
    dic = {
        1 : {"name" : "fury1","age" : 21 , "salary" : 15601},
        2 : {"name" : "fury2","age" : 22 , "salary" : 15602},
        3 : {"name" : "fury3","age" : 23 , "salary" : 15603},
    }
    print(dic)
    #增加一个K-V值
    print("===start===")
    dic[4] = {"name" : "fury4","age" : 24 , "salary" : 15604}
    print(dic)
    #删除字典中的所有内容,key 和 value一起删掉
    print("===one===")
    print(dic)
    # dic.clear()
    print(dic)
    # 浅复制(类似于列表list)
    print("===two===")
    dic1 = dic.copy()
    print(dic1)
    # dic1[1]["name"] = "fury"   # value值是一个字典时会是一改全改(类似于列表)
    # dic1[1] = "hello" # value值不是字典时,改的谁就是改的谁
    print(dic)
    print(dic1)
    print("===three===")
    dic2 = dic.fromkeys()
    print(dic2)
    字典元素的增加、删除、字典复制
    class dict(object):
        """
        dict() -> new empty dictionary
        dict(mapping) -> new dictionary initialized from a mapping object's
            (key, value) pairs
        dict(iterable) -> new dictionary initialized as if via:
            d = {}
            for k, v in iterable:
                d[k] = v
        dict(**kwargs) -> new dictionary initialized with the name=value pairs
            in the keyword argument list.  For example:  dict(one=1, two=2)
        """
    
        def clear(self): # real signature unknown; restored from __doc__
            """ 清除内容 """
            """ D.clear() -> None.  Remove all items from D. """
            pass
    
        def copy(self): # real signature unknown; restored from __doc__
            """ 浅拷贝 """
            """ D.copy() -> a shallow copy of D """
            pass
    
        @staticmethod # known case
        def fromkeys(S, v=None): # real signature unknown; restored from __doc__
            """
            dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.
            v defaults to None.
            """
            pass
    
        def get(self, k, d=None): # real signature unknown; restored from __doc__
            """ 根据key获取值,d是默认值 """
            """ D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None. """
            pass
    
        def has_key(self, k): # real signature unknown; restored from __doc__
            """ 是否有key """
            """ D.has_key(k) -> True if D has a key k, else False """
            return False
    
        def items(self): # real signature unknown; restored from __doc__
            """ 所有项的列表形式 """
            """ D.items() -> list of D's (key, value) pairs, as 2-tuples """
            return []
    
        def iteritems(self): # real signature unknown; restored from __doc__
            """ 项可迭代 """
            """ D.iteritems() -> an iterator over the (key, value) items of D """
            pass
    
        def iterkeys(self): # real signature unknown; restored from __doc__
            """ key可迭代 """
            """ D.iterkeys() -> an iterator over the keys of D """
            pass
    
        def itervalues(self): # real signature unknown; restored from __doc__
            """ value可迭代 """
            """ D.itervalues() -> an iterator over the values of D """
            pass
    
        def keys(self): # real signature unknown; restored from __doc__
            """ 所有的key列表 """
            """ D.keys() -> list of D's keys """
            return []
    
        def pop(self, k, d=None): # real signature unknown; restored from __doc__
            """ 获取并在字典中移除 """
            """
            D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
            If key is not found, d is returned if given, otherwise KeyError is raised
            """
            pass
    
        def popitem(self): # real signature unknown; restored from __doc__
            """ 获取并在字典中移除 """
            """
            D.popitem() -> (k, v), remove and return some (key, value) pair as a
            2-tuple; but raise KeyError if D is empty.
            """
            pass
    
        def setdefault(self, k, d=None): # real signature unknown; restored from __doc__
            """ 如果key不存在,则创建,如果存在,则返回已存在的值且不修改 """
            """ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """
            pass
    
        def update(self, E=None, **F): # known special case of dict.update
            """ 更新
                {'name':'alex', 'age': 18000}
                [('name','sbsbsb'),]
            """
            """
            D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
            If E present and has a .keys() method, does:     for k in E: D[k] = E[k]
            If E present and lacks .keys() method, does:     for (k, v) in E: D[k] = v
            In either case, this is followed by: for k in F: D[k] = F[k]
            """
            pass
    
        def values(self): # real signature unknown; restored from __doc__
            """ 所有的值 """
            """ D.values() -> list of D's values """
            return []
    
        def viewitems(self): # real signature unknown; restored from __doc__
            """ 所有项,只是将内容保存至view对象中 """
            """ D.viewitems() -> a set-like object providing a view on D's items """
            pass
    
        def viewkeys(self): # real signature unknown; restored from __doc__
            """ D.viewkeys() -> a set-like object providing a view on D's keys """
            pass
    
        def viewvalues(self): # real signature unknown; restored from __doc__
            """ D.viewvalues() -> an object providing a view on D's values """
            pass
    
        def __cmp__(self, y): # real signature unknown; restored from __doc__
            """ x.__cmp__(y) <==> cmp(x,y) """
            pass
    
        def __contains__(self, k): # real signature unknown; restored from __doc__
            """ D.__contains__(k) -> True if D has a key k, else False """
            return False
    
        def __delitem__(self, y): # real signature unknown; restored from __doc__
            """ x.__delitem__(y) <==> del x[y] """
            pass
    
        def __eq__(self, y): # real signature unknown; restored from __doc__
            """ x.__eq__(y) <==> x==y """
            pass
    
        def __getattribute__(self, name): # real signature unknown; restored from __doc__
            """ x.__getattribute__('name') <==> x.name """
            pass
    
        def __getitem__(self, y): # real signature unknown; restored from __doc__
            """ x.__getitem__(y) <==> x[y] """
            pass
    
        def __ge__(self, y): # real signature unknown; restored from __doc__
            """ x.__ge__(y) <==> x>=y """
            pass
    
        def __gt__(self, y): # real signature unknown; restored from __doc__
            """ x.__gt__(y) <==> x>y """
            pass
    
        def __init__(self, seq=None, **kwargs): # known special case of dict.__init__
            """
            dict() -> new empty dictionary
            dict(mapping) -> new dictionary initialized from a mapping object's
                (key, value) pairs
            dict(iterable) -> new dictionary initialized as if via:
                d = {}
                for k, v in iterable:
                    d[k] = v
            dict(**kwargs) -> new dictionary initialized with the name=value pairs
                in the keyword argument list.  For example:  dict(one=1, two=2)
            # (copied from class doc)
            """
            pass
    
        def __iter__(self): # real signature unknown; restored from __doc__
            """ x.__iter__() <==> iter(x) """
            pass
    
        def __len__(self): # real signature unknown; restored from __doc__
            """ x.__len__() <==> len(x) """
            pass
    
        def __le__(self, y): # real signature unknown; restored from __doc__
            """ x.__le__(y) <==> x<=y """
            pass
    
        def __lt__(self, y): # real signature unknown; restored from __doc__
            """ x.__lt__(y) <==> x<y """
            pass
    
        @staticmethod # known case of __new__
        def __new__(S, *more): # real signature unknown; restored from __doc__
            """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
            pass
    
        def __ne__(self, y): # real signature unknown; restored from __doc__
            """ x.__ne__(y) <==> x!=y """
            pass
    
        def __repr__(self): # real signature unknown; restored from __doc__
            """ x.__repr__() <==> repr(x) """
            pass
    
        def __setitem__(self, i, y): # real signature unknown; restored from __doc__
            """ x.__setitem__(i, y) <==> x[i]=y """
            pass
    
        def __sizeof__(self): # real signature unknown; restored from __doc__
            """ D.__sizeof__() -> size of D in memory, in bytes """
            pass
    
        __hash__ = None
    
    dict
    list

    》enumrate

      为可迭代的对象添加序号:返回值是序号和值,但是如果是字典类型的数据返回的值只是key值,没有value值

    lis = ["warrior", "fury", "happy"]
    for item1 in enumerate(lis):
        # print(item1[0],item1[1])
        # 优化:
        print(item1)
    
    dic = {
        1: "warrior",
        2: "fury",
        3: "happy",
    }
    
    for item in enumerate(dic):
        print(item[0], item[1])
    View Code
  • 相关阅读:
    Java并发包中Lock的实现原理
    多线程---再次认识volatile,Synchronize,lock
    共享锁(S锁)和排它锁(X锁)
    Java 7中的TransferQueue 以及 SynchronousQueue
    精巧好用的DelayQueue
    非阻塞同步算法与CAS(Compare and Swap)无锁算法
    彻底理解线索二叉树
    使用import取代require
    子页面iframe跨域执行父页面定义的JS方法
    利用js实现 禁用浏览器后退
  • 原文地址:https://www.cnblogs.com/NeverCtrl-C/p/6060676.html
Copyright © 2020-2023  润新知