一、python的数据类型

  1.python的基本数据类型包括数值数据类型和字符串数据类型;基本数据类型的特点是不允许改变,如果改变基本数据类型的值,会导致内存的重新分配。

  2.数值的相互转换函数

  3.变量的三个属性

  4.判断某个变量是否是某种类型实例

print(isinstance(3, float))            #False

  5.复数类型的使用

a = complex(2,2)
b = complex("3+2j")
print(a)
print(b)
print(a+b)
print(a-b)
print(a*b)
print(a/b)

(2+2j)
(3+2j)
(5+4j)
(-1+0j)
(2+10j)
(0.7692307692307692+0.15384615384615388j)

   6.python的字符串类型不像Java可以与数值类型相加,如“str”+1会报错,但python支持字符串与数值相乘,表示将字符串重复多少次。

#报错
#print("str"+1)
#重复字符串 print("The life is short,i love python\n" * 3) #The life is short,i love python #The life is short,i love python #The life is short,i love python
#转为大写 print("lower".upper()) #LOWER
#转为小写 print("UPPER".lower()) #upper

#去除前导和尾部空白 print(" hello python ".strip()) #hello python

#也可以指定去除的字符 print("##hello python##!".strip("#!")) #hello python

#求长度 print(len("hello")) #5

#拆分字符串 print("orange banana apple".split(" ")) #['orange', 'banana', 'apple']

#用指定字符串连接一个列表 print(" ".join(["orange","apple","banana","peach"])) #orange apple banana peach

#判断字符串是否以某个子串开始 print("good good study".startswith("go")) #True

#判断字符串是否以某个子串开始 print("day day up".endswith("up")) #True

#统计子串出现次数 print("Python is a nascent programming language.".count("p")) #1

#查找子串出现的下标 print("Sometimes your whole life boils down to one insane move.".find("wh")) #15

#判断是否是数字 print("moive".isdigit()) #False

#判断是否是字母 print("money".isalpha()) #True

#判断是否是空格 print("i declared".isspace()) #False

  7.Python的字符串最强大之处是切片操作

str = "Attitude determines altitude."
#取出Attitude(外国人的习惯是左闭右开,即包括左下标,不包括右下标)

print(str[0:9]) #Attitude

print(str[0:20:3]) #Aiddeis (每3个取一个)

print(str[-5:-1]) #tude

  8.Python的字符串可以用单引号,双引号,三引号表示,但字符串跨行时只能用三引号或反斜杠

str = '''Be
a
laborious
bee
'''

print(str) str1 = "Be \ a \ hard-working \ man" print(str1) #Be a hard-working man

  9.实现字符串反转

#切片 str[开始位置:结束位置:步数] 将步数设为-1
def strReverse1(str):
    return str[::-1]
#将字符串转为列表,反转后再连接为字符串 def strReverse2(str): newList = list(str) newList.reverse() return "".join(newList)
print(strReverse1("python")) print(strReverse2("python"))

二、输入输出

  1、输入函数input()

#输入一个字符串
myStr = input("请输入一个字符串:")
print(myStr)


#以逗号分割输入多个数
a,b,c = eval(input("请输入3个数:"))
print(a,b,c)

  2.输出函数 print()

#以逗号分割输出多个变量,输出后显示的分隔符是空格,结尾会输出一个换行符
print("i","am","studying","python")        #i am studying python

#指定分隔符和结尾符
print("i","am","studying","python",sep="#",end=" ")
print()

#类似c语言的输出
name = "jackson"
age = 22
salary = 5000.0
print("name:%s,age:%d,salary:%.3f" % (name,age,salary))

#python特有的输出形式
print("I like eating {} and {}".format("banana", "pear"))
print("His name is {name} and he is a {sex}".format(sex='male',name='judy'))
print("{1} can arm our {0}".format("brain","knowledge"))
print("The happiness rate of chinese citizen is up to {:.3f}".format(0.45))
print("The population of china is {:,d} million".format(1300))

三、集合数据类型

  Python的集合数据类型包括列表,元组,字典,集合

  

1.列表

#四种遍历方式
for item in fruits:
    print(item,end=" ")
print()
for item in iter(fruits):
    print(item,end=" ")
print()
for i,item in enumerate(fruits):
    print(i,"===>",item,end=" ")
print()
for item in range(len(fruits)):
    print(fruits[item],end=" ")
print()

#重复列表四次
print(fruits*4)                         #['orange', 'banana', 'pear', 'peach', 'orange', 'banana', 'pear', 'peach', 'orange', 'banana', 'pear', 'peach', 'orange', 'banana', 'pear', 'peach']
#列表连接
print(fruits+["pineapple","apple"])


#删除指定下标的元素,不提供参数则删除表尾元素
print(fruits.pop(2))                #['orange', 'banana', 'pear', 'peach', 'pineapple', 'apple']


#追加元素 append追加和extend追加有区别
#append追加的是列表
#extend追加的是元素
fruits.append(["Coconut"])
print(fruits)               #['orange', 'banana', 'peach', ['Coconut']]
fruits.pop()
fruits.extend(["Coconut"])
print(fruits)               #['orange', 'banana', 'peach', 'Coconut']


#列表反转
fruits.reverse()
print(fruits)               #['Coconut', 'peach', 'banana', 'orange']

#指定位置插入
fruits.insert(2, "nothing")
print(fruits)                #['Coconut', 'peach', 'nothing', 'banana', 'orange']


#删除列表切片
del fruits[1:3]
print(fruits)                #['Coconut', 'banana', 'orange']

  2.元组

myTuple1 = ("bird","plane","vehicle","subway")

#不能对单个元素重新赋值(报错)
#myTuple1[0] = "parrot"

#但可以对整个元组赋值
myTuple1 = ("python","c++","java")
print(myTuple1)                     #('python', 'c++', 'java')

#创建空元组
emptyTuple = ()
print(emptyTuple)                   #()


#注意创建一个元素的元组要在结尾加逗号
oneTuple = (1)
print(oneTuple)                     #1 不加逗号编译器会认为括号是进行算数运算,而不是创建元组
oneTuple = (1,)
print(oneTuple)                     #(1,)

#元组的取值 
print(myTuple1[0])                  #python
print(myTuple1[:])                  #('python', 'c++', 'java')
print(myTuple1[:1])                 #('python',)
print(myTuple1[len(myTuple1)-1:])   #('java',)

#元组的重复 
print(myTuple1 *4)                  #('python', 'c++', 'java', 'python', 'c++', 'java', 'python', 'c++', 'java', 'python', 'c++', 'java')

#元组相加
print(myTuple1 + ("one","two","three"))  #('python', 'c++', 'java', 'one', 'two', 'three')

  3.字典

myDict = {"one":1,"two":343.33,"three":True}

#字典的取值
print(myDict["one"])       #1

#判断键是否存在
print("three" in myDict)   #True


#更新值
myDict["one"] = 100
print(myDict)              #{'one': 100, 'two': 343.33, 'three': True}

#清空字典
myDict.clear()
print(myDict)              #{}

  4.集合

#以字符串创建set
mySet = set("hello")
print(mySet)                  #{'o', 'l', 'e', 'h'}


#以list创建set,自动去除重复元素
mySet1 = set(["a","m","e","o"])
print(mySet1)                 #{'o', 'a', 'm', 'e'}

#以map创建set,值为map的键
mySet2 = set({"name":1,"age":2})
print(mySet2)                 #{'name', 'age'}

#交集
print(mySet & mySet1)         #{'e', 'o'}

#并集
print(mySet | mySet1)         #{'l', 'a', 'e', 'h', 'm', 'o'}

#差集
print(mySet - mySet1)         #{'l', 'h'}

#对称差分运算
print(mySet ^ mySet1)         #{'l', 'a', 'h', 'm'}

四、强大的列表解析功能

import random
#列表解析
#生成10个随机数
list1 = [random.randint(0,100) for i in range(0,10)]
for item in list1:
    print(item,end=" ")         #74 38 75 45 96 1 38 93 58 80 
print()

list2 = [i*i for i in range(1,21)]
for num in list2:
    print(num,end=" ")          #1 4 9 16 25 36 49 64 81 100 121 144 169 196 225 256 289 324 361 400

#选出list2中的偶数
list3 = [i for i in list2 if i % 2 == 0]
for num in list3:
    print(num)                  #4 16 36 64 100 144 196 256 324 400

#按行遍历矩阵
list4 = [[1,2,3,4],[5,6,7,8],[2,3,4,5],[6,7,8,9]]
list5 = [[1,4,5,6],[2,1,3,4],[3,4,2,1],[7,8,2,1]]
print([row for row in list4])   #[[1, 2, 3, 4], [5, 6, 7, 8], [2, 3, 4, 5], [6, 7, 8, 9]]

#按列遍历矩阵
print([list4[row][1] for row in range(len(list4))])  #[2, 6, 3, 7]

#遍历对角线
print([list4[i][i] for i in range(len(list4))])      # [1, 6, 4, 9]

#逐个遍历
print([list4[row][col] for row in range(len(list4)) for col in range(len(list4[row]))])  #[1, 2, 3, 4, 5, 6, 7, 8, 2, 3, 4, 5, 6, 7, 8, 9]


#矩阵相加
print([list4[row][col] + list5[row][col] for row in range(list4.__len__()) for col in range(list4[row].__len__())])
#[2, 6, 8, 10, 7, 7, 10, 12, 5, 7, 6, 6, 13, 15, 10, 10]


#转置矩阵
print([row for row in zip(*list4)])  #[(1, 5, 2, 6), (2, 6, 3, 7), (3, 7, 4, 8), (4, 8, 5, 9)]

#求最大长度对应的字符
students = ["jack","shirely","kangkang","mary"]
maxLen = max([len(item) for item in students])
print(maxLen)
maxStr = [temp for temp in students if len(temp) == maxLen]
print(maxStr)                                     #['kangkang']

五、内置函数

#几个内置的高阶函数 map,filter,reduce,sorted
#map用于将一函数规则应用于一可迭代集合的所有元素
#reduce用于将一函数规则反复作用于一可迭代集合的元素,传入的函数参数必须为两个
#filter将一可迭代集合中适用于函数规则的元素挑选出来
#sorted用于对可迭代集合进行排序

#map的一个栗子(将字符串转为对应数字)
f = lambda ch:{"0":0,"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9}[ch]

f1 = lambda ch:int(ch)
print(list(map(f,"322")))                  #[3, 2, 2]


#reduce的一个栗子(将字符串转换为对应的十进制数)
def str2Decimal(x,y):
    return x*10 + y
print(reduce(str2Decimal,map(f,"232")))       #232


#filter的一个栗子(使用埃氏筛选法筛选素数)
seq = range(2,51)
for i in seq:
    f = lambda x : x == i or x % i
    seq = list(filter(f,seq))
print(list(seq))   #[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]

#sorted的一个栗子
rules = lambda x:x.lower()
reles2 = lambda x:x["age"]
students = ["jack","Nacy","Kangkang","asia"]
aMap = [{"name":"kangknag","age":25},{"name":"ag","age":13},{"name":"wnag","age":23}]
newlist = sorted(students, key=rules, reverse=False)
print(sorted(aMap,key=reles2))        #[{'name': 'ag', 'age': 13}, {'name': 'wnag', 'age': 23}, {'name': 'kangknag', 'age': 25}]
print(newlist)    #['asia', 'jack', 'Kangkang', 'Nacy']

先写到这吧,有点累。。。

03-18 05:13