zoukankan      html  css  js  c++  java
  • 条件,循环

    条件,循环及其它语句
    print:
    打印多个参数:打印多个表达式,用多个逗号分隔;还可自定义分隔符
    >>>print("greeting" + ',',"salutatiom","name") --->greeting, salutatiom name
    >>>print("greeting","salutatiom","name",sep="_") --->greeting_salutatiom_name
    import:
    导入模块:
    import somemodule
    from somemodule import somefunction
    from somemodule import *
    若有两个模块都包含相同的一个函数,如open(),这样调用函数open():
    module1.open() ---或 from module1 import open as open1
    module2.open() ---或 from module2 import open as open2
    另一种方法:在语句的末尾添加as子句并指定别名:
    >>>import math as foobar
    >>>foobar.sqrt(4) --->2.0
    导入特定函数并指定别名:
    >>>from math import sqrt as foobar
    >>>foobar(9) --->3.0
    赋值:
    1、序列解包:将一个序列或任何可迭代对象解包,并将得到的值储存到一系列的变量中:
    同时给多个变量赋值:(要解包的序列所包含的元素个数必须与在等号左边的列出的目标个数相同,否则python将引发异常,即等号的左右两边的个数相同)
    >>>x,y,z = 1,2,3
    >>>print(x,y,z) --->1 2 3
    >>>values = 4,5,6
    >>>values --->(4, 5, 6)
    >>>x,y,z = values
    >>>x --->4
    >>>scoundrel={"name": 'robin',"age": 30}
    >>>key,value = scoundrel.popitem()
    >>>key --->age
    >>>value --->30
    另:可用星号运算符(*)来收集多余的值,这样就无需保持变量和值的个数相同:但带星号(*)的变量最终包含的总是一个列表
    >>>a,b,c,*test = [1,2,3,4,5,6,7,8]
    >>>c --->3
    >>>test --->[4, 5, 6, 7, 8]
    将带星号(*)的变量放在其它位置:
    >>>name = "Albus Percival Wulfric Brian Dombledore"
    >>>first,*middle,last = name.split()
    >>>middle --->['Percival', 'Wulfric', 'Brian']
    链式赋值:将多个变量关联到同一个值
    增强赋值:如:x += 1,x *=2,fnord +='bar',fnord *=2
    ---------------------------------------------
    条件语句
    布尔值
    用作布尔表达式时:视为假:False None 0 "" () [] {}
    if、else、elif语句:
    name = input("what is your name?")
    if name.endswith('gumby'):
    print("hello,Mr.gubmy")
    else:
    print("hello,stranger")
    条件表达式:三目运算符的Python
    status = "friend" if name.endswith("gumby") else "strenger"
    代码嵌套:
    name = input("what is your name?")
    if name.endswith('gumby'):
    if name.startswith("Mr."):
    print("hello,Mr.gubmy")
    elif name.startswith("Mrs."):
    print("hello,Mrs.gubmy")
    else:
    print("hello,gubmy")
    else:
    print("hello,stranger")
    比较运算符:
    相等运算符(==):确定两个对象是否相等
    相同运算符(is):确定两个对象是否相同
    x is y
    x is not y
    >>>x=[1,2,3]
    >>>y=[2,4]
    >>>x is not y --->True
    >>>del x[2] --x:[1, 2]
    >>>y[1]=1
    >>>y.reverse() --y:[1, 2]
    >>>x is y --->False
    成员资格检查(in):
    字符串和序列的比较:
    字符串是根据字符的字母排列顺序进行比较的,字母是unicode字符,是按码点排列的。要获取字母的顺序值,可使用函数ord(这个函数与函数chr相反)
    >>>ord("a") --->97
    其它序列比较:
    >>>"a".lower() < "B".lower() --->True
    >>>[1,2] < [2,1] --->True
    >>>[2,[1,4]] < [2,[1,5]] --->True
    运算符(and,or,not):布尔运算符
    --------------------------------
    循环:while,for
    while循环:
    name = ""
    while not name: --while not name or name.isspace 或 while not name.strip() 输入的字符中除去空格
    name=input("please enter your name: ")
    print("Hello,{}!.format(name))
    for循环:
    可迭代对象是可使用for循环进行遍历的对象
    words = ['this','is','an','ex','parrot']
    for word in words:
    print(word)
    创建范围的内置函数range()
    >>>range(0,10) --->range(0, 10)
    >>>list(range(0,10)) --->[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    包含起始位置(0),但不包含结束位置(10)
    迭代字典:
    遍历所有的关键字:
    d = {'x': 1,'y': 2,'z':3}
    for key in d :
    print(key,'corresponds to',d[key])
    运行结果:
    x corresponds to 1
    y corresponds to 2
    z corresponds to 3
    可以使用keys等字典方法来获取所有的键。可使用d.values获取值。d.items以元组的方式返回键-值对
    for key,value in d.items():
    print(key,'corresponds to',value)
    运行结果:
    x corresponds to 1
    y corresponds to 2
    z corresponds to 3
    迭代工具:
    1、并行迭代:
    同时迭代两个序列:
    names=['anne','beth','george','damon']
    ages=[20,25,30,40]
    for i in range(len(names)):
    print(names[i],'is',ages[i],'years old')
    运行结果:
    nne is 20 years old
    beth is 25 years old
    george is 30 years old
    damon is 40 years old
    注:i是用作循环索引的变量的标准名称。
    内置函数zip:将两个序列缝合起来,并返回一个由元组组成的序列。返回的值时一个适合迭代的对象,要查看其内容,可使用list将其转换为列表。
    >>>names=['anne','beth','george','damon']
    >>>ages=[20,25,30,40]
    >>>list(zip(names,ages)) --->[('anne', 20), ('beth', 25), ('george', 30), ('damon', 40)]
    缝合后可在序列中将元组解包:
    for name,age in zip(names,ages):
    print(name,'is',age,'years old')
    运行结果:
    anne is 20 years old
    beth is 25 years old
    george is 30 years old
    damon is 40 years old
    函数zip可用于缝合任意数量的序列,当序列的长度不同是,函数zip在最短的序列用完后停止缝合。
    2、迭代时获取索引
    strings=['anne','beth','george','damon']
    for string in strings:
    if 'xxx' in string:
    index=strings.index(string) #在字符串列表中查找字符串
    strings[index]='[censored]'
    ------------
    index=0
    for string in strings:
    if 'xxx' in string:
    strings[index]='[censored]'
    index +=1
    -------------
    3、反向迭代和排序后迭代
    函数:reversed和sored (类似于列表的reverse和sort)
    可用于任何序列或可迭代的对象,且不就地修改对象,而是返回反转和排序后的版本:
    >>>sorted([4,2,6,9,0,2,5]) --->[0, 2, 2, 4, 5, 6, 9]
    >>>sorted("hello,world") -->[',', 'd', 'e', 'h', 'l', 'l', 'l', 'o', 'o', 'r', 'w']
    >>>list(reversed("hello,world")) --->['d', 'l', 'r', 'o', 'w', ',', 'o', 'l', 'l', 'e', 'h']
    >>>"".join(reversed("hello,world")) --->'dlrow,olleh'
    注:sorted返回的是一个列表,而reversed返回的是一个可迭代的对象,不能直接对它进行索引或切片操作,也不能直接对它调用列表的方法,要执行这些操作,可先使用list对返回的对象进行转换。
    跳出循环:
    1、break:跳出循环,直接中断循环
    2、continue:结束当前的迭代,并跳到下一次的迭代开头(结束本次循环,继续下一次的循环)
    pass、del、exec语句:
    pass:什么都不做,可将其用作占位符
    del:删除
    >>>x = ["hello","world"]
    >>>y=x
    >>>y --->['hello', 'world']
    >>>y[1]="python"
    >>>y --->['hello', 'python']
    >>>x --->['hello', 'python']
    >>>del x
    >>>y --->['hello', 'python']
    >>>x --->NameError: name 'x' is not defined
    注:x和y指向同一个列表,但删除x对y没有任何影响。删除x只是删除了名称x,而没有删除列表本身。
    exec、eval:使用exec和eval执行字符串即计算其结果
    exec:函数exec将字符串作为代码执行
    >>>exec("print('hello,world')") --->hello,world
    调用exec函数时,应向其提供命名空间(用于放置变量的地方)
    >>>from math import sqrt
    >>>scope={}
    >>>exec('sqrt = 1',scope)
    >>>sqrt(4) --->2.0
    >>>scope['sqrt'] --->1
    注:通过exec执行的赋值语句创建的变量置于scope中,而不会覆盖函数sqrt
    eval:计算用字符串表示的python表达式的值,并且返回结果
    >>>eval(input("enter an arithmetic expression: "))
    enter an arithmetic expression: 6+9*8
    --->78
  • 相关阅读:
    FFT最新卡常研究
    NOI2019赛前两周被吊打记录
    【NOI2019模拟2019.7.1】为了部落 (生成森林计数,动态规划)
    【NOI2019模拟2019.7.1】三格骨牌(轮廓线dp转杨图上钩子定理)
    Pytorch学习之源码理解:pytorch/examples/mnists
    [转载] ReLU和BN层简析
    Python的argparse模块的使用
    [转载]Pytorch中nn.Linear module的理解
    Pytorch中nn.Dropout2d的作用
    Pytorch中randn和rand函数的用法
  • 原文地址:https://www.cnblogs.com/skyzy/p/9432957.html
Copyright © 2011-2022 走看看