zoukankan      html  css  js  c++  java
  • 笔记1 python入门学习笔记

    官方手册

    https://docs.python.org/3.7/tutorial/index.html

    菜鸟站手册地址:

    https://www.runoob.com/python3/python3-basic-operators.html

    python的运行方法

    1. Sublime编辑器执行python代码,用Ctrl+b
    2. cmd黑窗口里 D:phpStudyPHPTutorialWWWpython>python test.py

    注释

    确保对模块, 函数, 方法和行内注释使用正确的风格

    Python中的注释有单行注释和多行注释:

    Python中单行注释以 # 开头,例如:

    三个单引号,或者三个双引号

        '''这是一个区块连的函数,
    		money:交易的金额
    		last_value 获取到数组的最后一个单元(默认值为[1])
    		Docstring'''
    

    参考手册:

    https://www.runoob.com/python3/python3-comment.html


    小技巧:

    input()接收用户输入的内容(默认为字符串)

    amount = float(input('请输入金额: '))

    print()

    打印输出

    由于我们正在讨论格式问题,就要注意 print 总是会以一个不可见的“新一行”字符( )结尾,因此重复调用 print将会在相互独立的一行中分别打印。为防止打印过程中出现这一换行符,你可以通过 end 指定其应以空白结尾:

    print('a', end='')
    print('b', end='')
    

    输出结果如下:

    ab

    或者你通过 end 指定以空格结尾:

    print('a', end=' ')
    print('b', end=' ')
    print('c')
    

    输出结果如下:

    a b c

    字符串拼接变量的输出

    str2=2 + 3 * 4
    a1 ='str 的值是' + str(str2)
    a1 ='str 的值是' + str2 #报错,字符串不和字数拼接
    print (a1) #str 的值是14
    print ('str 的值是' ,str2) #str 的值是 14
    

    运算符

    is 是判断两个标识符是不是引用自一个对象

    a = [20,30]
    b = [20,30]
    c = a 
    if ( a is b ):
       print ("1 - a 和 b 有相同的标识")
    else:
       print ("1 - a 和 b 没有相同的标识")
     
    if ( a is c ):
       print ("5 - a 和 c 有相同的标识")
    else:
       print ("5 - a 和 c 没有相同的标识")
    
    if ( id(a) == id(b) ):
       print ("2 - a 和 b 有相同的标识")
    else:
       print ("2 - a 和 b 没有相同的标识")
     
    # 修改变量 b 的值
    b = 30
    if ( a is b ):
       print ("3 - a 和 b 有相同的标识")
    else:
       print ("3 - a 和 b 没有相同的标识")
     
    if ( a is not b ):
       print ("4 - a 和 b 没有相同的标识")
    else:
       print ("4 - a 和 b 有相同的标识")
    

    输出:

    1 - a 和 b 没有相同的标识
    5 - a 和 c 有相同的标识
    2 - a 和 b 没有相同的标识
    3 - a 和 b 没有相同的标识
    4 - a 和 b 没有相同的标识
    

    https://www.runoob.com/python3/python3-basic-operators.html

    all和any

    1. all相当于and并且
    2. any相当于or或者
    test_list = [1,2,3,4,-5]
    test = [el > 0 for el in test_list] #[True, True, True, True, False]
    print(all(test)) #False   
    print(any(test)) #True   
    

    强制类型转换

    type()

    打印数值类型

    float()

    将字符串的数字转为浮点型

    str()

    将数字转为字符串

    int()

    将浮点型转为整型

    a = 12.5
    a = int(12.5)
    print(a) #输出:12 向下取整
    

    标准数据类型

    Python3 中有六个标准的数据类型:

    Number(数字)
    String(字符串)
    List(列表)
    Tuple(元组)
    Set(集合)
    Dictionary(字典)

    Python3 的六个标准数据类型中:

    不可变数据(3 个):Number(数字)、String(字符串)、Tuple(元组)。 # 数字无
    可变数据(3 个):List(列表)、Dictionary(字典)、Set(集合)。     # 列字集
    

    类型可以看成一个对象.
    help() 后连按加回车 可以查看类型下面的函数
    如:

    • help(str)
    • help(list)

    判断数据类型

    a = {1,2}
    # if isinstance(a,str):
    # if isinstance(a,int):
    # if isinstance(a,list):
    if isinstance(a,):
    	print(True)
    else:
    	print(False)
    

    列表 集合 元组 字典 的特性介绍

    # animal = ['pig','dog','cat','dog','pig'] #列表
    # animal = {'pig','dog','cat','dog','pig'} #集合
    # animal = ('pig','dog','cat','dog','pig') #元组
    # animal = {'name':'lisi','age':28,'weight':120} #字典
    
    类型 特性 符号
    列表 可编辑 有序 允许重复 []
    集合 可编辑 无序 不可重复 {}
    元组 不可编辑 有序 可重复 ()
    字典 无序 可编辑 值:可重复 键:不可重复 键值对形式 {}

    各种数据结构的各种操作

    类型 列表推导 for循环 索引 拆包 符号
    列表 可以 可以 可以 可以 []
    集合 可以 可以 不可以 可以 {}
    元组 可以 可以 可以 可以 ()
    字典 可以 可以 可以 可以 {}

    变量

    1. 变量可以理解为一个空盒子,向变量赋值可以理解为向空盒子子里存东西,向变量重新赋值可以理解为把盒子里原有的东西拿出来,放入新的东西
    2. 声明变量前不需加任何声明.php前需要加$,JavaScript前需要加var,python不需要
    3. 变量分为局部变量全局变量,局部变量可以通过global转为全局变量

    #变量的赋值(也叫拆包)
    list = ('wangwu',28)
    name,age=list
    print(name,age) #wangwu 28
    
    
    #定义global全局变量
    name = 'lisi'
    def get_name():
        global name
        name = input('please input your are name:')
        
    get_name() #运行函数局部变量就会通过global转为全局变量
    
    print(name) #输出的是input里您输入的值
    

    字符串

    字符串的拼接

    a= 'hello'
    b='word'
    c = a + b
    print ("值为:", c) # 'helloword'
    

    字符串的重复输出

    str='la' * 3
    print (str) #lalala
    

    字符串的换行

    方法一.用三个单引号或者三个双引号

    str= '''asdfasdfasdf
    asdfasdfasdfdfasdf
    asdfasdfasdfdfasdf
    '''
    print (str)
    

    输出

    asdfasdfasdf
    asdfasdfasdfdfasdf
    asdfasdfasdfdfasdf
    

    方法二.用 符号换行

    'This is the first line
    This is the second line'
    

    输出

    This is the first line
    This is the second line
    

    字符串的不换行

    str= "This is the first sentence. 
    This is the second sentence."
    print (str)
    

    输出

    This is the first sentence. This is the second sentence.
    

    字符串for循环

    st = 'abcdefg'
    for s in st :
        print(s)
    

    输出:

    a
    b
    c
    d
    e
    f
    g
    

    format() 格式化方法

    name = 'lisi'
    age = '28'
    
    # new_str = 'I am '+ name +' and I am '+ age +' years old.'
    # new_str = 'I am {} and I am {} years old.'.format(name, age)
    # new_str = 'I am {0} and I am {1} years old. I like my name {0}'.format(name, age) #用索引可以重复调用
    # new_str = 'I am {name} and I am {age} years old.' #变量不会解析
    # new_str = 'I am {name} and I am {age} years old.'.format(name = name, age = age)
    # print(new_str)
    
    funds = 123.456
    # new_str = 'Funds: {0:f}'.format(funds)
    # <:居右  >:居左  ^:居中 0是点位符,冒号后面的是要输出的符号, 10是共计输出多少位, 
    # f是转为浮点数(默认保留小数点后四位),f前可以指定小数点后保留多少位,
    new_str2 = 'Funds:|{0:-^10.2f}|'.format(funds)
    
    print(new_str2) #Funds:|--123.46--|
    
    print(f"{'lisi':-^20}") #--------lisi--------
    
    

    更多例子:

    https://bop.mol.uno/07.basics.html

    f格式化

    name ='tongpan'
    # age = 28
    # person = {'name':'tongpan', 'age':28}
    # new_str = f"I am {person['name']} and I am {person['age']+2} years old." 
    # <:居右  >:居左  ^:居中 0是点位符,冒号后面的是要输出的符号, 10是共计输出多少位, 
    # f是转为浮点数(默认保留小数点后四位),f前可以指定小数点后保留多少位,
    # new_str = f"|{name:-^20}|" #|------tongpan-------|
    # new_str = f"|{name:->20}|" #|-------------tongpan|
    new_str = f"|{name:-<20}|" #|tongpan-------------|
    # pi = 3.1415926
    # new_str = f"{pi:.3f}" # 3.142 保留三位小数,四舍五入
    print(new_str)
    

    %格式化

    1. 打印单个变量
     # 整形:%d
     # 字符串类型:%s
     # 浮点类型: %f (几位小数就写几f 如:12.45 %2f)
    
     # 字符串变量类型的格式化
     name = 'zhiliao'
     print('my name is %s'%name)
    
     # 整形变量的格式化
     age = 2147483648
     print('my age is %d'%age)
    
     # 浮点类型变量的格式化
     price = 18.9
     print("apple's price is %f"%price)
     print("apple's price is %.2f"%price)
    
    1. 打印多个变量
     name = 'zhiliao'
     age = 18
     gender = 'boy'
     # 元组
     print('my name is %s,my age is %d,gender is %s'% (name,age,gender))
    
    1. 其他打印方式:
     # 如果想字符串的末尾打印一个变量,那么可以采用以下方式
     age = 18
     print('my age is',age)
    
     # 如果是其他数据类型,使用%s的方式进行格式化
     # 那么其实,Python是首先将这个数据转换为字符串
     # 再进行格式化。
     age = 18
     print('my age is %s'%age)
    

    格式化总结

    name = 'lisi'
    age = 20
    gender =  '男'
    # str1 = 'my name is %s,age is %d,gender is %s'% (name,age,gender) #my name is lisi,age is 20,gender is 男
    # str1 = 'my name is {},age is {},gender is {}'.format(name,age,gender) #my name is lisi,age is 20,gender is 男
    str1 = f'my name is {name},age is {age},gender is {gender}' #my name is lisi,age is 20,gender is 男
    print(str1)  
    
    info = {}
    info['name']=name
    info['age']=age
    info['gender']=gender
    # str2 = 'my name is %s,age is %d,gender is %s'% (info['name'],info['age'],info['gender']) #my name is lisi,age is 20,gender is 男
    # str2 = 'my name is {},age is {},gender is {}'.format(info['name'],info['age'],info['gender']) #my name is lisi,age is 20,gender is 男
    str2 = f"my name is {info['name']},age is {info['name']},gender is {info['gender']}" #my name is lisi,age is 20,gender is 男
    print(str2)
    
    print(info['name']) #lisi
    print(info['age'])  #20
    # print(info['color'])  #20 报异常
    

    转义字符

    new_str = 'Im tongpa
    '
    '
    "
    
    
    
    a
    	
     
    f  
    N 
    v 
    ooo 
    xhh 
    Uxxxxxx
    uxxxx
    print(new_str)
    

    手册:
    https://www.runoob.com/python3/python3-string.html


    列表 (相当于PHP里的索引数组)

    参考菜鸟手册
    https://www.runoob.com/python3/python3-list.html

    • 相当里php里的数组
    • 序列中的每个元素都分配一个数字 - 它的位置(索引),第一个索引是0,第二个索引是1,依此类推。
    list1 = ['Google', 'Runoob', 1997, 2000];
    list2 = [1, 2, 3, 4, 5, 6, 7 ];
     
    print ("list1[0]: ", list1[0]) #list1[0]:  Google 
    print ("list2[1:5]: ", list2[1:5]) #list2[1:5]:  [2, 3, 4, 5]
    

    列表的添加

    列表相当于php中的一维数组,里面元素是有序的,可以重复的.

    1. 向列表的最后面追加单元数据

    列表的追加(向数组的右边追加) append()方法

    list1 = ['Google', 'Runoob', 'Taobao']
    list1.append('Baidu')
    print ("更新后的列表 : ", list1) #['Google', 'Runoob', 'Taobao', 'Baidu']
    
    1. 向数组后面拼接元素
    list1 = ['Google', 'Runoob', 'Taobao']
    n = ['a','b','c']
    list1 += n
    print(list1) #['Google', 'Runoob', 'Taobao', 'a', 'b', 'c']
    
    1. insert() 函数用于向列表指点任意列表的插入值。

    insert()方法 list.insert(index, obj)

    list1 = ['Google', 'Runoob', 'Taobao']
    list1.insert(1, 'Baidu')
    print ('列表插入元素后为 : ', list1) #['Google', 'baidu', 'Runoob', 'Taobao']
    
    1. extend() 函数用于在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)。

    extend()方法语法:

    list.extend(seq)

    list1 = ['Google', 'Runoob', 'Taobao']
    list2=list(range(5)) # 创建 0-4 的列表
    list1.extend(list2)  # 扩展列表
    print ("扩展后的列表:", list1) # ['Google', 'Runoob', 'Taobao', 0, 1, 2, 3, 4]
    

    5.extend 与 append 的区别

    • extend 与 append 方法的相似之处在于都是将新接收到参数放置到已有列表的后面。
    • 而 extend 方法只能接收 list,且把这个 list 中的每个元素添加到原 list 中。
    • 而 append 方法可以接收任意数据类型的参数,并且简单地追加到 list 尾部。
    list1 = ['Google', 'Runoob', 'Taobao']
    list1.extend(['a','b'])  # 扩展列表
    print (list1) # ['Google', 'Runoob', 'Taobao', 'a', 'b']
    
    list2 = ['Google', 'Runoob', 'Taobao']
    list2.append(['a','b'])  # 扩展列表
    print (list2) # ['Google', 'Runoob', 'Taobao', ['a', 'b']]
    

    https://www.runoob.com/python3/python3-att-list-extend.html

    列表的删除

    方法一:可以使用 del 语句来删除列表的指定元素,如下实例:

    list = ['Google', 'Runoob', 1997, 2000]
    print ("原始列表 : ", list) #原始列表 :  ['Google', 'Runoob', 1997, 2000]
    del list[2]
    print ("删除第三个元素 : ", list) #删除第三个元素 :  ['Google', 'Runoob', 2000]
    

    方法二:remove()

    描述

    remove() 函数用于移除列表中某个值的第一个匹配项。

    语法

    remove()方法语法:
    list.remove(obj)

    list1 = ['Google', 'Runoob', 'Taobao', 'Baidu']
    list1.remove('Taobao')
    print ("列表现在为 : ", list1) #列表现在为 :  ['Google', 'Runoob', 'Baidu']
    list1.remove('Baidu')
    print ("列表现在为 : ", list1) #列表现在为 :  ['Google', 'Runoob']
    

    方法三:pop(列表索引)

    描述
    pop(列表索引) 函数用于移除列表中某索引的值

    不列索引,默认删除最后一个元素

    list = ['Google', 'Runoob', 1997, 2000]
    list.pop(2) 
    print(list) #['Google', 'Runoob', 2000]
    

    列表的更新 指定列表里元素的索引下标重新赋值

    你可以对列表的数据项进行修改或更新,如下所示:
    指定列表里元素的索引下标重新赋值

    list = ['Google', 'Runoob', 1997, 2000]
    print ("第三个元素为 : ", list[2]) #第三个元素为 :  1997
    list[2] = 2001
    print ("更新后的第三个元素为 : ", list[2]) #更新后的第三个元素为 :  2001
    

    列表截取(切片)与拼接

    Python的列表截取与字符串操作类型.

    如下所示:

    L=['Google', 'Runoob', 'Taobao']

    Python 表达式 结果 描述
    L[2] 'Taobao' 读取第三个元素
    L[-2] Runoob' 从右侧开始读取倒数第二个元素: count from the right
    L[1:] ['Runoob', 'Taobao'] 输出从第二个元素开始后的所有元素
    L[:] ['Google', 'Runoob', 'Taobao'] 输出所有元素

    拼接

    list1 = ['Google', 'Runoob', 'Taobao']
    n = ['a','b','c']
    list1 += n
    print(list1) #['Google', 'Runoob', 'Taobao', 'a', 'b', 'c']
    

    嵌套列表

    把两个一维列表嵌套成一个两维列表

    a = ['Google', 'Runoob', 'Taobao']
    b = ['a','b','c']
    c = [a,b]
    print(c) #[['Google', 'Runoob', 'Taobao'], ['a', 'b', 'c']]
    

    列表的赋值

    copy()和直接=赋值的区别:

    1. 使用=直接赋值,是引用赋值,更改一个,另一个同样会变
    2. copy() 则顾名思义,复制一个副本,原值和新复制的变量互不影响

    例子:
    https://www.runoob.com/python3/python3-att-list-copy.html

    # 列表的传值赋值 (原列表a数据值改变,不影响赋值的新列表b)
    a=[0,1,2,3,4,5]
    # 列表的传值赋值的几种方法
    # b=a.copy() #copy()函数传值赋值
    # b=a[:] #切片传值赋值
    b=a[0:] #切片传值赋值
    a[0] = 6
    print(a)  #[6, 1, 2, 3, 4, 5]
    print(b)  #[0, 1, 2, 3, 4, 5]
    
    # 列表的引用赋值 (原列表a和新列表c指的是同一个列表在内存里的地址,可以理解为同一个列表起的不同的别名)
    # 原列表c数据值改变,新列表b的值也改变
    c=[0,1,2,3,4,5]
    d=c
    c[0] = 6
    print(c)  #[6, 1, 2, 3, 4, 5]
    print(d)  #[6, 1, 2, 3, 4, 5]
    

    元组

    Python 的元组与列表类似,不同之处在于元组的元素不能修改。

    元组使用小括号,列表使用方括号。

    相同之处,它们的元素都是有序的,可以重复的

    元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可。

    手册:
    https://www.runoob.com/python3/python3-tuple.html


    序列

    列表、元组和字符串可以看作序列(Sequence)的某种表现形式,可是究竟什么是序列,它又有什么特别之处?

    序列的主要功能是资格测试(Membership Test)(也就是 in 与 not in 表达式)和索引操作(Indexing Operations),它们能够允许我们直接获取序列中的特定项目。

    上面所提到的序列的三种形态——列表、元组与字符串,同样拥有一种切片(Slicing)运算符,它能够允许我们序列中的某段切片——也就是序列之中的一部分。

    案例(保存为 ds_seq.py):

    shoplist = ['apple', 'mango', 'carrot', 'banana']
    name = 'swaroop'
    
    # Indexing or 'Subscription' operation #
    # 索引或“下标(Subscription)”操作符 #
    print('Item 0 is', shoplist[0])
    print('Item 1 is', shoplist[1])
    print('Item 2 is', shoplist[2])
    print('Item 3 is', shoplist[3])
    print('Item -1 is', shoplist[-1])
    print('Item -2 is', shoplist[-2])
    print('Character 0 is', name[0])
    
    # Slicing on a list #
    print('Item 1 to 3 is', shoplist[1:3])
    print('Item 2 to end is', shoplist[2:])
    print('Item 1 to -1 is', shoplist[1:-1])
    print('Item start to end is', shoplist[:])
    
    # 从某一字符串中切片 #
    print('characters 1 to 3 is', name[1:3])
    print('characters 2 to end is', name[2:])
    print('characters 1 to -1 is', name[1:-1])
    print('characters start to end is', name[:])
    

    输出:

    Item 0 is apple
    Item 1 is mango
    Item 2 is carrot
    Item 3 is banana
    Item -1 is banana
    Item -2 is carrot
    Character 0 is s
    Item 1 to 3 is ['mango', 'carrot']
    Item 2 to end is ['carrot', 'banana']
    Item 1 to -1 is ['mango', 'carrot']
    Item start to end is ['apple', 'mango', 'carrot', 'banana']
    characters 1 to 3 is wa
    characters 2 to end is aroop
    characters 1 to -1 is waroo
    characters start to end is swaroop
    

    手册:

    https://bop.mol.uno/12.data_structures.html

    字典

    为什么需要字典:

    有时候我们需要存储一组相关的数据的时候,

    比如要存储一个人的信息,那么有username,age,birthday等,

    如果这些信息都存储在列表中,或者数组中,

    比如['username','age','birthday']那么用起来可能不是很方便。

    比较方便的操作是,我直接通过username这个key就可以拿到这个值,

    我通过username就可以给这个key设置值,

    那么就可以通过字典的方式实现我们的需求。

    字典 可以理解为键值对形式的json格式字符串形式 或者 php中的关联数组

    1. 字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})中 ,

      格式如下所示:

      d = {key1 : value1, key2 : value2 }

    2. 字典是另一种可变容器模型,且可存储任意类型对象。

    3. 键必须是唯一的,但值则重复。

    4. 值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组。

    5. 元素是无序的

    一个简单的字典实例:

    dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}

    创建字典:

    #方法一:
    dict1 = { 'abc': 456 };
    dict2 = { 'abc': 123, 98.6: 37 };
    
    #方法二:
    info = {}
    info['name']=name
    info['age']=age
    info['gender']=gender
    
    #输出
    print(info) #{'name': 'lisi', 'age': 20, 'gender': '男'}
    print(info['name']) #lisi
    print(info['age'])  #20
    # print(info['color'])  #20 报异常
    
    # 也可以指定一个,在没有获取到这个值时候的默认值
    print(info.get('color','red')) #red
    
    方法三:使用dict函数:
    person = dict(username='zhiliao',age=18) #{'username': 'zhiliao', 'age': 18}
    print(person)
    

    基本操作:

    • len(d):返回字典的键值对的长度。
    • d[k]:获取k这个key对应的值。
    • d[k] = v:设置键为k的值为v,如果字典中不存在键为k的这一项,那么自动的添加进去。
    • del d[k]:删除d这个字典中键为k的这一项数据。
    • k in d:检查d这个字典中是否包含键为k的这一项。
    • 字典中的键可以是任意的不可变类型,比如:浮点类型、整形、长整形、字符串或者元组。

    字典常用方法:

    1. clear:清除字典中所有的项。

      a = {'username':'zhiliao','age':18}
      print(a) #{'username': 'zhiliao', 'age': 18}
      a.clear()
      print(a) #{}
      
    2. get:访问字典中那个键对应的那个值。这个方法不会抛出异常。

      a = {'username':'zhiliao','age':18}
      username = a.get('username')
      print(username) #print(city) 
      
      city = a.get('city') # 获取到的是一个None。
      print(city) #None
      
      # 也可以指定一个,在没有获取到这个值时候的默认值
      city = a.get('city','changsha') 
      print(city) #changsha
      
      # city = a['city'] 
      # print(city) # 抛出异常
      
    3. pop:用来获得对应于给定键的值,然后将这个键和值的项从字典中删除。会返回这个值。

      d = {'x':1,'y':2}
      b=d.pop('x')
      print(b) # 1
      print(d) # {'y': 2}
      
    4. popitem:随机的移除字典中的一项。因为字典是无序的,所以是随机的。

      d= {'name': '菜鸟教程', 'alexa': 10000, 'url': 'www.runoob.com'}
      a=d.popitem() # 随机弹出一个值
      print(d) # {'name': '菜鸟教程', 'alexa': 10000}
      print(a) #('url', 'www.runoob.com')
      
    5. update:用一个字典更新另外一个字典,如果碰到相同的键,则会覆盖。

      a = {'url':'http://www.baidu.com/','title':"baidu"}
      b = {"url":"http://www.google.com/",'new_value':"new_value"}
      a.update(b)
      print(a) #{'url': 'http://www.google.com/', 'title': 'baidu', 'new_value': 'new_value'}
      
    6. setdefault:如果字典中包含有给定键,则返回该键对应的值,否则返回为该键设置的值。

    7. key in dict
      if k in dict:判断某个键是否在字典中存在。

      
      dict = {'Name': 'Runoob', 'Age': 7}
      
      # 检测键 Age 是否存在
      if  'Age' in dict:
          print("键 Age 存在")
      else :
          print("键 Age 不存在")
       
      # 检测键 Sex 是否存在
      if  'Sex' in dict:
          print("键 Sex 存在")
      else :
          print("键 Sex 不存在")
       
      # not in
       
      # 检测键 Age 是否存在
      if  'Age' not in dict:
          print("键 Age 不存在")
      else :
          print("键 Age 存在")
          
      # 以上实例输出结果为:
      
      # 键 Age 存在
      # 键 Sex 不存在
      # 键 Age 存在    
      
      

    遍历字典:

    1. 遍历字典中所有的key:使用keys方法,这个方法将所有的键以列表的方式返回。
      a = {"url":"www.baidu.com",'title':"baidu"}
      for x in a.keys():
          print x
      
    2. 遍历字典中所有的key:使用iterkeys方法,这个方法将返回一个迭代器,用来遍历所有的键的。
      a = {"url":"www.baidu.com",'title':"baidu"}
      for x in a.iterkeys():
          print x
      
    3. 遍历字典中所有的value:使用values方法,这个方法将所有的值以列表的方式返回。
      a = {"url":"www.baidu.com",'title':"baidu"}
      for x in a.values():
          print x
      
    4. 遍历字典中所有的value:使用itervalues方法,这个方法将返回一个迭代器,用来遍历所有的值。
      a = {"url":"www.baidu.com",'title':"baidu"}
      for x in a.itervalues():
          print x
      
    5. 遍历字典中所有的键值对:使用items方法,这个方法将所有的键和值以列表的方式返回。
      a = {"url":"www.baidu.com",'title':"baidu"}
      for key,value in a.items():
          print key
          print value
      
    6. 遍历字典中所有的键值对:使用iteritems方法,这个方法将返回一个迭代器,用来遍历所有的键和值。
      a = {"url":"www.baidu.com",'title':"baidu"}
      for key,value in a.iteritems():
          print key
          print value
      

    手册:
    https://www.runoob.com/python3/python3-dictionary.html

    直接赋值和 copy 的区别

    可以通过以下实例说明:

    dict1 = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
    dict2 = dict1.copy()
    print ("新复制的字典为 : ",dict2) #新复制的字典为 :  {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
    
    dict1 =  {'user':'runoob','num':[1,2,3]}
    dict2 = dict1          # 浅拷贝: 引用对象
    dict3 = dict1.copy()   # 浅拷贝:深拷贝父对象(一级目录),子对象(二级目录)不拷贝,还是引用
     
    # 修改 data 数据
    dict1['user']='root'
    dict1['num'].remove(1) 
     
    # 输出结果
    print(dict1) #{'user': 'root', 'num': [2, 3]}
    print(dict2) #{'user': 'root', 'num': [2, 3]}
    print(dict3) #{'user': 'runoob', 'num': [2, 3]}
    

    浅拷贝和深拷贝的区别

    https://www.runoob.com/w3cnote/python-understanding-dict-copy-shallow-or-deep.html


    函数

    def 自定义一函数

    def test():
    	print('My name is haima')
    test() #My name is haima
    

    详情:

    https://bop.mol.uno/10.functions.html

    https://www.runoob.com/python3/python3-function.html


    循环

    for循环

    blockchian = [[[1], 12.0], [[[1], 12.0], 13.0], [[[[1], 12.0], 13.0], 14.0]]
    for block in blockchian:
    	'''这是一个区块连的函数,
    		money:交易的金额
    		last_value 获取到数组的最后一个单元(默认值为[1])
    		Docstring'''
    	print(block)
    

    while循环

    while True:
        print('请输入数字:')
        print('1:继续交易')
        print('2:打印当前区块链')
        print('q:退出当前操作')
        userChoice_num = get_userChoice_num()
        if userChoice_num == '1':
            money = get_input_money()
            add_value(money,get_last_value())
        elif userChoice_num == '2':
            print_blockchian()
        elif userChoice_num == 'q':
            break #continue
        else:
            print('请输入列表里的数字!')
    

    range()函数循环列表

    也可以使range以指定数字开始并指定不同的增量(甚至可以是负数,有时这也叫做'步长'):

    for i in range(0, 10, 3) :
        print(i)
    

    打印结果:

    0
    3
    6
    9
    

    手册参考

    https://www.runoob.com/python3/python3-loop.html

    判断if..elif..else

    ```python
    if userChoice_num == '1':
        money = get_input_money()
        add_value(money,get_last_value())
    elif userChoice_num == '2':
        print_blockchian()
    elif userChoice_num == 'q':
        break #continue
    else:
        print('请输入列表里的数字!')
        
        
        
    value = int(input('请输入你的值,输入整形:'))
    
    if value == 1:
        print('今天是星期一')
    elif value == 2:
        print('今天是星期二')
    elif value == 3:
        print('今天是星期三')
    elif value == 4:
        print('今天是星期四')
    elif value == 5:
        print('今天是星期五')
    elif value == 6:
        print('今天是星期六')
    elif value == 7:
        print('今天是星期日')
    else:
        print('请输入1-7的整数')  
    ```
    

    手册参考

    https://www.runoob.com/python3/python3-conditional-statements.html

    breakcontinue的区别

    break终止本次循环
    continue跳过当前操作,执行下一次循环

    数据的推导式

    例子一:

    list = [1,2,3,4,5]
    newlist = [li*2 for li in list]
    print(newlist) #[2, 4, 6, 8, 10]
    
    #加if条件筛选出符合条件的元素再做操作
    list = [1,2,3,4,5]
    newlist = [li*2 for li in list if li % 2==0]
    print(newlist) #[4, 8]
    
    list = [1,2,3,4,5]
    items = [1,3]
    newlist = [el*2 for el in list if el in items]
    print(newlist) #[2, 6]
    
    numb = [1, 2, 3, 4, 5, 6, 7]
    num = '-'.join([str(v*2) for v in numb]) #join是把列表数组里的每一个值循环出来,用-号连接转为字符串
    print(num) #输出:2-4-6-8-10-12-14
    

    例子二:

    字典的列表推导

    方法一(只能拿到键):
    animal = {'name':'tongpan', 'age':28, 'weight':120}
    print([el for el in animal]) #['name', 'age', 'weight']
    
    方法二(键,值都能拿到):
    animal = {'name':'tongpan', 'age':28, 'weight':120}
    a = animal.items() #items把字典转为这种形式dict_items([('name', 'tongpan'), ('age', 28), ('weight', 120)])
    for k,v in a:
        print(k,v)
        print('---------------------')
        
    # 打印结果
    # name tongpan
    # ---------------------
    # age 28
    # ---------------------
    # weight 120
    # ---------------------
    
    
    list1 = [('name','lisi'),('age',18),('gender','man')]
    # 循环列表里的元组,拿到元组的k和v,再存为字典
    zidian = {key:value for (key,value) in list1}
    print(zidian) #{'name': 'lisi', 'age': 18, 'gender': 'man'}
    
    
    list1 = [('name','lisi'),('age',18),('gender','man')]
    print([key for (key,value) in list1]) #['name', 'age', 'gender']
    print([value for (key,value) in list1]) #['lisi', 18, 'man']
    
    
    
    

    例子三:

    list0 = [('name','lisi','red'),('age',18,'prink'),('gender','man','purple')]
    list1 = [('name','lisi'),('age',18),('gender','man')]
    # 循环列表里的元组,拿到元组的k和v,再存为别的类型的
    list_a = [vv for (key,value,vv) in list0] 
    list_c = {vv for (key,value,vv) in list0} 
    list_b = {value:vv for (key,value,vv) in list0}
    list_d = [vv for (key,value,vv) in list0 if vv=='red']
    list2 = {key for (key,value) in list1} 
    list3 = {value for (key,value) in list1}
    list_e = ' '.join(str(vv) for (key,value,vv) in list0) #red prink purple
    
    print(list_a) #['red', 'prink', 'purple']
    print(list_c) #{'red', 'purple', 'prink'}
    print(list_b) #{'lisi': 'red', 18: 'prink', 'man': 'purple'}
    print(list_d) #['red']
    
    print(list2) #{'gender', 'name', 'age'}
    print(list3) #{'lisi', 18, 'man'}
    print(list_e) #red prink purple
    

    例子四:

    abc= [('name','lisi','red'),('age',18,'prink'),('gender','man','purple')]
    #key当前的索引(脚标),value是当前的值
    for (key,value) in enumerate(abc):
        print(key,value)
    

    打印:

    0 ('name', 'lisi', 'red')
    1 ('age', 18, 'prink')
    2 ('gender', 'man', 'purple')
    

    例子五:

    aa = {'name':'tongpan', 'age':28, 'weight':120}
    # 能拿到当前元素的索引(脚标:index)
    for (index,key) in enumerate(aa):
        print(index,key,aa[key])
    
    for key in aa:
        print(key,aa[key])
    

    打印结果

    0 name tongpan
    1 age 28
    2 weight 120
    name tongpan
    age 28
    weight 120
    

    拆包

    test_list = [1,2,3,4,-5]
    #拆包 就是批量赋值 变量的数量要和list里的元素个数对上
    a,b,c,d,e=test_list 
    print(a,b,c,d,e) #1 2 3 4 -5
    
  • 相关阅读:
    【Node.js】Jade视图模板的使用
    【Node.js】新建一个NodeJS 4.X项目
    【Node.Js】npm国内被墙的解决方法
    【AngularJS学习笔记】Java Script "use strict" 严格模式
    【Linux学习笔记】Linux-CentOS下安装Redis
    【Linux学习笔记】常用命令速记
    【AngularJS学习笔记】封装一些简单的控件(封装成Html标签)
    数组和切片1
    Go错误处理机制及自定义错误
    内置函数
  • 原文地址:https://www.cnblogs.com/haima/p/9955928.html
Copyright © 2011-2022 走看看