当前位置: 移动技术网 > IT编程>脚本编程>Python > 初学Python的一些细节

初学Python的一些细节

2019年03月18日  | 移动技术网IT编程  | 我要评论

dojanboni,范晓微,风筝下载

一、python的数据类型

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

int 整形

         二进制       a = 0b1010

     八进制        a = 0o37

  十进制        a = 25

       十六进制     a = 0x34a

float 浮点型 f1 = 0.12,f2 = 1.343e-3
bool 布尔型 flag = true  
complex 复数类型 a = complex(2,3)

 

 

 

 

 

 

 

 

  2.数值的相互转换函数

转十六进制 hex()
转八进制 oct()
转二进制 bin()
转整形 int()

 

 

 

 

  3.变量的三个属性

标识 变量的内存地址,可以用id()查看
类型 变量的类型,可以用type()查看
存储的值

 

 

 

  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的集合数据类型包括列表,元组,字典,集合

列表 list(内部元素可以重新赋值,列表和列表可以相加,列表和数字可以相乘) arr = ["jack"]
元组 tuple(内部元素不能重新赋值,元组可以和元组相加,元组可以和数字相乘) mytuple = ("nacy","rose")
字典 dict(无序,可重新赋值,键唯一,值不唯一,键为不可变元素) mymap = {"name":"zhangshan","age":12}
集合 set(无序,唯一,可进行集合间的交并差补) myset1= set(["judy","tom","martin"]) myset2 = set("lily")

 

 

 

 

  

 

 

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']

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

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网