Pyhton基础语法

349 阅读13分钟

1. Python变量与字符串

1.1 Python数据类型

数据类型 分类
Number(数字) int、float、bool、complex、long
String(字符串) NULL
List(列表) NULL
Tuple(元组) NULL
Set(集合) NULL
Dictionary(字典) NULL
Bool(布尔) NULL
  1. 不可变数据(变量对应的值中的数据是不能被修改,如果修改就会生成一个新的值从而分配新的内存空间):Number、String、Tuple、Bool
  2. 可变数据(变量对应的值中的数据可以被修改,但内存地址保持不变):List、Dictionary、Set

1.2 字符串操作

  1. int len(String) --> String长度

  2. String String.find(str[,strat_index,end_index]) --> 正序索引,str是否在String中,如果是返回开始的索引,否则,返回-1

  3. String String.rfind(str[,start_index,end_index]) --> 倒序索引,str是否在String中,如果是返回开始的索引,否则,返回-1

  4. String String.index(str[,start_index,end_index]) --> 正序索引,str是否在String中,如果是返回开始的索引,否则,报错

  5. String String.rindex(str[,start_index,end_index]) --> 倒序索引,str是否在String中,如果是返回开始的索引,否则,报错

  6. int String.count(str[,start_index,end_index]) --> String中str的次数

  7. String String.replace(str1,str2,count) --> 将String中的str1替换为str2,最多替换count次

  8. String String.capitalize() --> String第一个字母大写

  9. String String.title() --> String每一个单词首字母大写

  10. String String.lower() --> String大写转小写

  11. String String.upper() --> String小写转大写

  12. String String.strip() --> 删除String两端空白字符

  13. String String.lstrip() --> 删除String左边空白字符

  14. String String.rstrip() --> 删除String右边空白字符

  15. List String.splitlines() --> 按行分割

  16. List String.split(str) -->按str分割

    len("hello") --> 5  #1
    string="hello"
    string.find("e") --> 1  #2
    string.rfind("l")  --> 3  #3
    string.index("e") --> 1  #4
    string.rindex("l") --> 3  #5
    string.count("l") --> 2  #6
    string.replace("l","e",3) --> "heeeo"  #7
    string.capitalize() --> "Hello" #8
    "this is a test".title() --> "This Is A Test"  #9
    "HELLO".lower() --> "hello"  #10
    string.upper() --> "HELLO"  #11
    " hello ".strip() --> "hello"  #12
    " hello ".lstrip() --> "hello "  #13
    " hello ".rstrip() --> " hello"  #14
    "a\nb\nc\nd".splitlines() --> ["a","b","c","d"]  #15
    "a,b,c,d".split(",") --> ["a","b","c","d"]  #16
    

    ==c/c++/java中字符为单引号(‘ ’),字符串为双引号(“ ”).python中单引号和双引号都为字符串==

    ==python支持a=b=c=1的赋值==

1.3 输入输出与格式化输出

1.3.1 输入

  1. String input(your_hint)

1.3.2 输出

1.3.2.1 输出
  1. print()
1.3.2.2 字符串格式化输出
  1. format函数使用(有占位符无索引)

    print("{} love {}".format("I","you"))
    
    Result:
    	I love you
    
  2. format函数使用(有占位符有索引)

    print("{1} love {0}".format("you","I"))
    
    Result:
    	I love you
    
  3. format函数使用(有占位符有别名)

    print("{blank1} love {blank0}".format(blank0="you",blank1="I"))
    
    Result:
        I love you
    
1.3.2.3 数字格式化输出
  1. 保留小数

    print(format(123.456,"0.2f"))
    
    Result:
        123.45
    
  2. 千分位分割符

    print(format(123456,","))
    
    Result:
        123,456
    
  3. 货币格式输出

    print(format(123456,"0,.2f"))
    
    Result:
        123,456.00
    
1.3.2.3 数字和字符串格式化输出
print("My name is {} , my weight is {:0.2f}".format("Jack",123.456))

Result:
	My name is Jack , my weight is 123.46
1.3.2.4 早期格式化输出
print("My name is %s , I am %d years old , My weight is %0.2f kg."%("Jack",25,120))

Result:
    My name is Jack , I am 25 years old , My weight is 		 120.00 kg.

1.4 注释

语言 样式
c/c++/java //注释一行
/* ...... */ 注释若干行(编译器可以看懂)
/**……*/文档注释
python #
‘’’……….‘’’
“””………“””

2. Pyhton流程控制语句

2.1 控制语句

python --> if-elif-else
c/c++ --> if-else && if-else if-else && switch-case-defalut
java --> if-else && if-else if-else && switch-case(->)-defalut

2.2 循环控制

python --> while && while-else && for-in && for-in-else
c/c++/java --> while && do-while && for && for(:)

2.3 跳出循环

c/c++/java/python --> 
contiue --> 跳出当前循环
break --> 跳出多重循环

3. 常用运算符的使用

3.1 与c/c++/java不同的运算符

无三目运算符(? :)
**  2**3=8 幂运算,相当于pow(x,y)
/  10/3=3.33333 除法运算,而在c/c++/java中还要看数据类型
//  向下取整的除法 
i++/i-- python中不存在
in  数据是否在其中
is  是否指向同一块内存
not

4. 列表与字典

4.1 列表(List)

4.1.1 介绍

  1. 列表中数据结构按顺序排列
  2. 列表有正序和倒序两种索引(正序索引从0开始,倒序索引从-1开始)
  3. 列表可储存任意类型的数据,且允许重复

4.1.2 列表的创建

  1. list=[1,2,”3”,”4”]
  2. list=[]

4.1.3 列表的取值

  1. 索引取特定值与范围值

  2. int List.index(string value) --> 传入List中的值,获取第一次出现的位置,如果不存在,则报错

    list=[1,2,3,4,5]
    list[2] --> 3
    list[-3] --> 3
    list.index(2) --> 1
    list.index(0) --> ValueError
    

4.1.4 遍历列表

  1. for(迭代变量)-in(可迭代对象)

    fruits=["apple","banana","orange","apple"]
    for fruit in fruits:
        print("I like ",fruit)
        
    Result:I like  apple
    	   I like  banana
           I like  orange
           I like  apple   
    
  2. while循环

    i=0
    while i<len(fruits):
        print("I like ",fruits[i])
        i+=1
        
    Result:I like  apple
    	   I like  banana
           I like  orange
           I like  apple    
    

4.1.5 列表的反转与排序

  1. void List.reverse() -–> 将列表反转并更新列表

    list=[8,7,6,5,4,3,2,1]
    list.reverse()
    list --> [1,2,3,4,5,6,7,8]
    
  2. void List.sort()-->正序排列并更新原列表

    list=[1,4,5,7,4,2,3,6]
    list.sort()
    list --> 1,2,3,4,4,5,6,7
    
  3. void List.sort(reverse=True) -->倒序排列并更新原列表

    list=[1,4,5,7,4,2,3,6]
    list.sort(reverse=True)
    list --> 7,6,5,4,4,3,2,1
    

4.1.6 列表的新增、修改、删除操作

  1. void List.append(new_element) -->列表末尾追加新元素,括号中什么就追加什么

  2. void List.insert(index,new_element) -->指定索引插入新元素

  3. void List[index]=new_element -->更新指定索引位置数据

  4. void List[begin_index:end_index]=NewList -->更新指定范围数据

  5. void List.remove(old_element) -->删除指定元素,只删除一个

  6. Deleted_Element List.pop(index) -->按索引删除指定元素

  7. void List[begin_index:end_index]=[] -->删除

  8. 可以使用元组运算符(+ *)

    list=[1,2,3,4,5]
    list.append(6)  #1
    list --> [1,2,3,4,5,6]
    list.insert(0,0)  #2
    list --> [0,1,2,3,4,5,6]
    list[0]=2  #3
    list --> [2,1,2,3,4,5,6]
    list[0,2]=[3,4]  #4
    list --> [3,4,2,3,4,5,6]
    list.remove(3)  #5
    list --> [4,2,3,4,5,6]
    list.pop(0) --> 4  #6
    list --> [2,3,4,5,6]
    list[0:2]=[]  #7
    list --> [4,5,6]
    

4.1.7 列表其它常用方法

  1. int List.count(element) --> List中元素数量

  2. void List.append(append_list) --> 将append_list/element加入到List

  3. void List.extend(append_list) --> 将append_list中元素放入List

  4. boolean element in List --> element是否在List中

  5. newList List.copy() / = --> 复制List,不指向一块内存 / 指向同一块内存

  6. boolean List1 is List2 --> List1、List2是否指向同一块内存

  7. void List.clear() --> 清空List

    list=[1,2,3,4,5,1]
    list.count(1) --> 2  #1
    list.extend([1,2,3])  #3
    list --> [1,2,3,4,5,1,1,2,3]
    list.append([1,2])  #2
    list --> [1,2,3,4,5,1,1,2,3,[1,2]]
    1 in list -->True  #4
    list1=list.copy()  #5
    list1 --> [1,2,3,4,5,1,1,2,3,[1,2]]
    list2=list  #5
    list2 --> [1,2,3,4,5,1,1,2,3,[1,2]]
    list1 is list --> False  #6
    list2 is list --> True  #6
    list.clear()  #7
    list --> []
    

4.1.8 项目中的使用场景:嵌套列表

  1. [[name,age,salary],[name,age,salary],[name,age,salary],[name,age,salary]]

  2. 实例

    empList = []
    while True:
        string = input("Please input info:")
        if string == "":
            print("Exited")
            print(empList)
            break
        else:
            personalList = string.split(",")
            if len(personalList) == 3:
                empList.append(personalList)
            else:
                print("Input info is wrong")
               
    Result:
        Please input info:jack,27,5000
        Please input info:marry,30,5000
        Please input info:
        Exited
        [['jack', '27', '5000'], ['marry', '30', '5000']]
    

4.1.9 列表储存数据的问题

  1. 列表在表达结构化数据时语义不明确
  2. 结构化数据是指有明确属性,明确表示规则的数据

4.2 字典(Dictionary)

4.2.1 特点

  1. 采用键值对的形式(key:value)表示
  2. key不可以重复,value可以重复
  3. 可变数据,改变值其储存空间不变

4.2.2 创建

  1. {}

  2. Dict dict(key1=value1,.....)函数

  3. Dict dict.fomKeys([key1,key2,....],default_value=None)

    dictionary1={“name”:"Jack","sex":"male","age":25}
    type(dictionary1) --> <class 'dict'>
    dictionary1 --> {'name': 'Jack', 'sex': 'male', 'age': 25}
    dictionary2=dict.fromkeys(["name","sex","age"],"unknown")
    type(dictionary2) --> <class 'dict'>
    dictionary2 --> {'name': 'unkonown', 'sex': 'unkonown', 'age':'unknown'}
    

4.2.3 取值(查)

  1. value Dict[key]

  2. value Dict.get(key[,default_value])

    dictionary={“name”:"Jack","sex":"male","age":25}
    dictionary["name"] --> 'Jack'
    dictinnary["grade"] --> NameError
    dictionary.get("name") --> 'Jack'
    dictionary.get("grade") --> 
    dictionary.get("grade","unkonwn") --> 'unknown'
    

4.2.4 字典遍历

  1. for key in Dict:\n ......

    dictionary={"name":"Jack","age":"25"}
    for key in dictionary:
        print(key,"---",dictionary[key])
        
    Result:
        name --- Jack
    	age --- 25
    
  2. for key,value in Dict.items():\n ......

    dictionary={"name":"Jack","age":"25"}
    for key,value in dictionary.items():
        print(key,"---",value)
        
    Result:
    	name --- Jack
    	age --- 25
    

4.2.5 字典的增删改操作

  1. Dict[key]=new_value

  2. void Dict.update({key1:new_value1,key2:value2,.....})

  3. 增操作与改操作相同,有则更新,无则增加(上面两种方法都可以)

  4. value Dict.pop(key) --> 删除key对应的一项

  5. Tuple Dict.popitem() --> 删除最后一项

  6. void Dict.clear() --> 清空字典

    dict={"name":"Jack","sex":"male","age":"25"}
    dict --> {'name': 'Jack', 'sex': 'male', 'age': '25'}
    dict["job"]="police"  #1
    dict --> {'name': 'Jack', 'sex': 'male', 'age': '25', 'job': 'police'}
    dict["age"]=25  #3
    dict --> {'name': 'Jack', 'sex': 'male', 'age': 25, 'job': 'police'}
    dict.update({"dpt":"indentification","sal":5000})  #2
    dict --> {'name': 'Jack', 'sex': 'male', 'age': 25, 'job': 'police', 'dpt': 'indentification', 'sal': 5000}
    dict.pop("dpt") --> 'indentification'  #4
    dict --> {'name': 'Jack', 'sex': 'male', 'age': 25, 'job': 'police', 'sal': 5000}
    dict.popitem() --> ('sal', 5000)  #5
    dict --> {'name': 'Jack', 'sex': 'male', 'age': 25, 'job': 'police'}
    dict.clear()  #6
    dict --> {}
    

4.2.5 字典的其它操作

  1. value Dict.setdefault(key,value) --> 设置默认值,如果key存在,可以忽略

  2. Dict_keys Dict.keys()

  3. Dict_values Dict.values()

  4. Dict_items Dict.items()

  5. 2、3、4都是获取字典视图,字典变化,视图变化

  6. 老版本字典格式化字符串“%(key1)s,%(key2)s" %Dict

  7. python3之后字典格式化字符串 “{key1},{key2}”.format_map(Dict)

    dict={"name":"Jack","sex":"male","age":"25"}
    dict["dept"] --> KeyError
    dict.setdefault("deft","None") --> 'None'
    dict["dept"] --> KeyError
    type(dict.keys) --> <class 'builtin_function_or_method'>
    type(dict.values) --> <class 'builtin_function_or_method'>
    type(dict.items) --> <class 'builtin_function_or_method'>
    print("%(name)s--%(age)s"%dict) --> Jack--25
    print("{name}--{age}".format_map(dict)) --> Jack--25
    

4.2.5 散列值(Hash)和字典的储存原理

  1. int hash(value) --> 在多次运行时,数据是不一样的
  2. 字典储存原理:将Key先转换为Hash值,再在对应内存空间中放入Value。内存地址==Key Hash值。所以,字典中储存数据不是按顺序来。
  3. 字典在内存中不连续储存,列表连续储存。

4.2.5 应用

  1. 在C++课设中,房间信息可以用字典来储存

5. 元组与集合

5.1 元组(Tuple)

5.1.1介绍

  1. Tuple是不变List,创建之后不能修改,只能创建,本身元素只能查操作(元组中有列表,则列表中数据可以写),且查操作与List相同
  2. Tuple使用()

5.1.2 元组运算符

  1. Tuple3=Tuple1+Tuple2

  2. Tuple2=Tuple*count

  3. 元组运算符适用于列表,但是前后类型应该相同

    [1,2,3]+[4,5,6] --> [1, 2, 3, 4, 5, 6]
    [1,2,3]*3 --> [1, 2, 3, 1, 2, 3, 1, 2, 3]
    (1,2,3)+(4,5,6) --> (1, 2, 3, 4, 5, 6)
    (1,2,3)*2 --> (1, 2, 3, 1, 2, 3)
    (1,)*2 --> (1, 1)
    (1)*2 --> 2
    [1]*2 --> [1, 1]
    

5.1.2 元组创建

  1. (element,…….)
  2. element,……..
  3. 元组只有一个元素时,元素后面必须要有逗号,否则视为普通括号中的其它数据

5.1.3 列表与元组的区别和应用

  1. 内容:List内存中内容可以改变,Tuple内存中内容不可改变
  2. 内存:List内存动态变化,Tuple内存固定不变
  3. 效率:List效率低,Tuple效率高
  4. 使用:List用于保存运行时需要变化的数据,Tuple用于保存不用改变的数据

5.2 序列

5.2.1 介绍

  1. 序列中元素是有序的
  2. 序列是有索引的
  3. String、List、Tuple、Range(数字序列)都是序列,是数据结构的统称

5.2.2 数字序列的创建

  1. Range range(begin_num,edn_num[,step])

    range(1,4) --> range(1,4)
    range(1,10,2) --> range(1,10,2)
    

5.2.3 Range遍历其它序列和应用

  1. 遍历String
  2. 遍历List
  3. 遍历Tuple
  4. 质数

5.2.3 序列类型互相转换

  1. List list(sequence) --> 转换为列表

  2. Tuple tuple(sequence) --> 转换为元组

  3. String element.join(String_Tuple/List) String str() --> 转换为字符串

  4. List String.split(element) --> 传入分割元素,分割String,返回List

  5. List String.splitlies() --> 按行分割String

  6. for循环 --> 辅助使用,将数字转换为String

    #转换为List  #1,4,5
    list((1,2,3,4)) --> [1, 2, 3, 4]
    list("abcd") --> ['a', 'b', 'c', 'd']
    list(range(0,11,2)) --> [0, 2, 4, 6, 8, 10]
    "1,2,3,4".split(",") --> ['1', '2', '3', '4']
    "1\n2\n3\n4".splitlines() --> ['1', '2', '3', '4']
    #转换为Tuple  #2
    tuple("hello") --> ('h', 'e', 'l', 'l', 'o')
    tuple([1,2,3]) --> (1, 2, 3)
    tuple(range(1,5)) --> (1, 2, 3, 4)
    #转换为String
    #使用到join()函数  #3
    ",".join("hello") --> 'h,e,l,l,o'
    ",".join(("a","b","c")) --> 'a,b,c'
    ",".join(["a","b","c"]) --> 'a,b,c'
    "".join(("a","b","c")) --> 'abc'
    "".join(["a","b","c"]) --> 'abc'
    #使用str()函数  #3
    str(["a","b","c"] --> "['a', 'b', 'c']"
    str(range(1,5)) --> 'range(1, 5)'
    str(("a","b")) --> "('a', 'b')"
    #range()-->String  #6
    string = ""
    for i in range(1,5):
        string+=str(i)
    string --> '1234'
    

5.3 集合(Set)

5.3.1 介绍

  1. 集合是没有value的字典,可以参考数学中集合
  2. 无序性、互异性
  3. 可变数据类型、允许数学运算、分散储存
  4. 集合生成Hash,Hash内存储存数据

5.3.2 集合的创建

  1. {}

  2. Set set(anthor_type(Tuple/String/List))

  3. 空集合的创建不能用{},应该用set()

    dict={}
    type(dict) --> <class 'dict'>
    set=set()
    type(set) --> <class 'set'>
    set={1,2,3}
    set((1,2,3)) --> {1,2,3}
    set([1,2,3]) --> {1,2,3}
    set("hello") --> {'l', 'o', 'e', 'h'}
    set(range(1,6)) --> {1, 2, 3, 4, 5}
    

5.3.3 集合的数学运算(交集、并集、差集)

  1. Set Set1.intersection(Set2)

  2. Set set1&set2 --> 交集

  3. void Set1.intersection_update(Set2)

  4. Set Set1.union(Set2)

  5. Set set1|set2 --> 并集

  6. void Set1.union(Set2) --> 不存在

  7. Set Set1.difference(Set2) 差集(Set1中Set2不存在的元素)

  8. Set set1-set2 --> 差集

  9. Set Set1.symmetric_difference(Set2) --> 双向差集,两个集合中都不存在的元素

  10. void Set1.difference_update(Set2)

  11. void Set1.symmetric_difference_update(Set2)

  12. set1,set2 --> 两个Set合成为一个Tuple

    set1={1,2,3,4,5}
    set2={4,5,6,7,8}
    #交集
    set1.intersection(set2) --> {4, 5}  #1
    set1&set2 --> {4, 5}  #2
    set1.intersection_update(set2)  #3
    set1 --> {4, 5}
    #并集
    set1={1,2,3,4,5}
    set1.union(set2) --> {1, 2, 3, 4, 5, 6, 7, 8}  #4
    set1|set2 --> {1, 2, 3, 4, 5, 6, 7, 8}  #5
    #差集
    set1.difference(set2) --> {1, 2, 3}  #7
    set1-set2 --> {1, 2, 3}  #8
    set1.symmetric_difference(set2) --> {1, 2, 3, 6, 7, 8}  #9
    set1.difference_update(set2)  #10
    set1 --> {1,2,3}
    set1={1,2,3,4,5}
    set1.symmetric_difference_update(set2)  #11
    set1 --> {1, 2, 3, 6, 7, 8}
    #合并为tuple
    set1={1,2,3,4,5}
    set2={4,5,6,7,8}
    st1,set2 --> ({1, 2, 3, 4, 5}, {4, 5, 6, 7, 8})  #12
    

5.3.4 集合间的关系操作

  1. Bool Set1==Set2

  2. Bool Set1.issubset(Set2) --> Set1是不是Set2的子集

  3. Bool Set1.issuperset(Set2) --> Set1是否为Set2的父集

  4. Bool Set1.isdisjoint(Set2) --> Set1和Set2中是否有重复元素

    # 2
    set1={1,2}
    set2={1,2,3}
    set1.issubset(set2) --> True
    set1={1,2,5}
    set1.issubset(set2) --> False
    # 3
    set1={1,2,3,4}
    set2={2,3}
    set1.issuperset(set2) --> True
    set2={7,8}
    set1.issuperset(set2) --> False
    # 4
    set1={1,2,3,4,5}
    set2={6,7,8,9}
    set1.isdisjoint(set2) --> True
    set1={6,7}
    set1.isdisjoint(set2) --> False
    

5.3.5 集合的增删

  1. void Set1.add(element)

  2. void Set1.update(Tuple/List/Dict)

  3. 不可直接改

  4. void Set.remove(element) --> 不存在报错

  5. void Set.discard(element) --> 不存在不报错

    set1={1,2,3,4,5}
    set1.add(0)  #1
    set1 --> {0, 1, 2, 3, 4, 5}
    set1={1,2,3,4,5}
    set1.update([6,7,8])  #2
    set1 --> {1, 2, 3, 4, 5, 6, 7, 8}
    set1={1,2,3,4,5}
    set1.update((6,7,8))  #2
    set1 --> {1, 2, 3, 4, 5, 6, 7, 8}
    set1={1,2,3,4,5}
    set1.update({6,7,8})  #2
    set1 --> {1, 2, 3, 4, 5, 6, 7, 8}
    set1={1,2,3,4,5}
    set1.update(range(10,16))  #2
    set1 --> {1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15}
    set1={1,2,3,4,5}
    set1.remove(1)  #4
    set1 --> {2, 3, 4, 5}
    set1.remove(0) -->KeyError  #4
    set1 --> {1,2,3,4,5}
    set1.discard(1)  #5
    set1 --> {2, 3, 4, 5}
    set1.discard(0)  #5
    

5.4 内置生成式

  1. 列表生成式 List=[i*10 for i in range(10,20)... if i%2 == 0...]

    list=[i*j for i in range(1,5) for j in range(1,5) if i%2==0]
    list
    
    Result:
    	[2, 4, 6, 8, 4, 8, 12, 16]
    
  2. 字典生成式 Dict={i*10 for i in range(10,20)... if i%2 == 0...}

    fruits=["apple","banana","orange"]
    dict={i:fruits[i] for i in range(0,len(fruits))}
    dict
    
    Result:
        {0: 'apple', 1: 'banana', 2: 'orange'}
    
  3. 集合生成式 Set={i*10 for i in range(10,20)... if i%2 == 0...}

    set={i*j for i in range(1,5) for j in range(1,5) if i%2==0}
    set
    
    Result:
    	{2, 4, 6, 8, 12, 16}