本文共 13275 字,大约阅读时间需要 44 分钟。
整数
n1 = 0b1010
n2 = 0o567
n3 = 0xfdc2
浮点数n1 = 3.14
n2, n3 = 3.2e6, 1.2e-3
简单数学函数内建函数
abs(num):
n1, n2, n3 = 1, 0, -1
print(abs(n1), abs(n2), abs(n3)) # 1 0 1max(num) 和 min(num):n1, n2, n3, n4 = 1, 2, 3, 4
print(max(n1, n2), min(n2, n3 , n4)) # 2 4li = [1, 2, 3, 4]
print(max(li)) # 4round(num, n]):pi = 3.14159
print(round(pi)) # 3print(round(pi, 3)) #3.142math模块中的函数ceil():
import math
pi = 3.14159print(round(pi)) # 3print(math.ceil(pi)) # 4print(round(pi + 0.5)) # 可以替代ceil()floor():import math
x = 3.678print(round(x)) # 4print(math.floor(x)) # 3print(floor(x - 0.5)) # 可以替代floor()sqrt():import math
print(math.sqrt(16)) # 4print(math.sqrt(17)) # 4.123105635随机函数random():
import randomprint(random.random()) # 生成[0, 1)的一个小数choice(seq):import randomli = [1, 2, 4, 5]print(random.choice(li)) # 从对应的列表中随机选择一个元素uniform(x, y):import randomprint(random.uniform(1, 3) # 得到[1, 3]之间的随机小数randint(x, y):import randomprint(random.randint(1, 5)) # [1, 5]之间的随机整数randrange(start, stop, step):import randomprint(random.randrange(2, 10, 2) # 参数类型与range()函数一样三角函数
import math
angle = 1 / 6 * math.pi # 30°, pi/6res1 = math.sin(angle) # 接收弧度值angle = math.radians(30) # 将角度值转换为弧度值res1 = math.cos(angle)布尔类型是 int 的子类型,计算时会自动转换为 int
print(2 + True) # 3
print(1 + False) # 1是一种单独的类型flag, tag = True, False
可以当作判定条件使用if True:
字符串
字符串表示方式
str = 'abc' # 单引号对
str = "abc" # 双引号对str = '''abc''' # 三个单引号str = """abc""" # 三个双引号str = "his name is 'rity', that is a good name"
str = "his name is 'rity', that is a good name"
str1 = "That's all"
str2 = r"That's all" print(str1) # That's allprint(str2) # That's allstr = "his name is 'rity', "
"that is a good name"str = ("his name is 'rity', ""that is a good name")"""
可以直接在三对双引号内进行换行多用于程序段的注释---end---"""字符串的操作一般操作
字符串拼接res1 = "abc" + "def"print(res1) # abcdefres2 = "abc" "def"print(res2) # abcdefres3 = "%s%S" % ("abc", "def")print(res3) # abcdef字符串的乘法res = "a" * 3print(res) # aaa字符串的切片str = "abcdefg"print(str[3]) # d
print(str[-1]) # gprint(str[::]) # abcdefg
print(str[0:len(str):1]) # agcdefgprint(str[::2]) #acegprint(str[::-1]) #gfedcba函数操作len():name1, name2 = "rity", "瑞迪"
print(len(name1), len(name2)) # 4 2find():str = "abcdabefg"
print(str.find("ab")) # 0print(str.find("ab", 1)) # 4print(str.find("xy")) # -1count():str = "abcda"
print(str.count("a")) # 2print(str.count("a", 2) # 1print(str.count("x")) # 0replace():str = "abacad"
print(str.replace("a", "A")) #AbAcAdprint(str.replace("a", "A", 2)) #AbAcadprint(str) # abacadljust() 和 rjust():str = "abc"
print(str.ljust(6, "x")) # abcxxxprint(str.rjust(6, "x")) # xxxabcprint(str) # abclstrip() 和 rstrip() 和 strip()name = "xi am rity ."
print(name.lstrip("ix")) # | am rity .|print(name.rstrip(". ") # |xi am rity|print(name.strip("ix.")) # | am rity |split():info = "rity,nanchang,158-7926-7420"
res = info.split(",")print(res) # ['rity', 'nanchang', '158-7926-7420']num = "12 3 4"
res = num.split(" ")print(res) # ['12', '', '3', '4']str = "a c b "
res = str.split()print(res) # ['a', 'c', 'b'] 省略首尾的空白字符,将中间连续的空白字符视作一个分隔符进行分隔partition():pi = 3.14159
res1 = pi.partition(".")res2 = pi.partition("-")print(res1) # ('3', '.', '14159')print(res2) # ('3.14159', '', '')join():li = ["137", "9878", "0098"]
res1 = "-".join(li)res2 = "".join(li)print(res1) # 137-9878-0098print(res2) # 13798780098isalpha(), isdigit(), isalnum()str1, str2, str3, str4, str5 = "agcD", "123", "2j3e4ef", ""print(str1.isalpha()) # Trueprint(str2.isdigit()) # Trueprint(str4.isalnum()) # Trueprint(str5.isalpha(), str5.isdigit(), str5.isalnum()) # False False Falsestartswith() 和 endswith()name = "2018-08-09: xxx报告"
file = "xxx.md"print(name.startswith("2018")) # Trueprint(file.endswith(".md")) # True列表有序可变元素的集合
表示方式
li = ["a", "b", "c"]
li = ["a", "b", 1, 2, True]
li = [[1, 2, 3], 2, True, "hehe"]
li = list(range(1, 4)) # [1, 2, 3]
li = list("abc") # ('a', 'b', 'c')nums = [1, 2, 3, 4, 5]
li = [n*n for n in nums if n % 2]print(li) # [1, 9, 25]常用操作append():
nums = [1, 2, 3, 4]
nums.append(5)print(nums) # [1, 2, 3, 4, 5]insert:nums = [1, 2, 3, 4]
nums.insert(1, 9)print(nums) # [1, 9, 2, 3, 4]extend():nums1, nums2 = [1, 2], [3, 4]
nums1.extend(nums2)print(nums1) # [1, 2, 3, 4]del语句:nums = [1, 2, 3]del nums[0]print(nums) # [2, 3]pop():
nums = [1, 2, 3]
res = nums.pop()print(nums, res) # [1, 2] 3remove():names = ["Rity", "Jack", "Tom"]
names.remove("Jack")print(names) # ["Rity", "Tom"]nums = [1, 2, 2, 3, 4, 2]
for n in nums:if n == 2:nums.remove(n)print(nums) # [1, 3, 4, 2]index():li = [12, 34, 99]
idx = li.index(34)print(idx) # 1count():li = [1, 1, 2, 3, 5]
print(li.count(1)) # 2切片:参考字符串切片列表遍历:val = ["a", "b", "a", "d"]
currentIdx = 0 # 解决index("a")恒为0的问题for v in val:idx = val.index(v, currentIdx)print(idx, v)currentIdx += 1idxList = list(range(0, len(val)))
for idx in idxList:print(idx, val[idx])val = ["a", "b", "c", "d"]
print(list(enumerate(val))) # [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]for idx, val in enumerate(val):print(idx, val)排序s = "acgehijd"
res = sorted(s)print(res) # ['a', 'c', 'd', 'e', 'g', 'h', 'i', 'j']print(sorted(s), reverse=True) # ['j', 'i', 'h', 'g', 'e', 'd', 'c', 'a']def getKey(x):
return x[1]li = [("s0", 18), ("s1", 17), ("s2", 16)]
res0, res1 = sorted(li), sorted(li, key=getKey)print(res0) # [("s0", 18), ("s1", 17), ("s2", 16)] print(res1) # [("s2", 15), ("s1", 17), ("s0", 18)]li = [1, 3, 5, 2, 0]
li.sort()print(li) # [0, 1, 2, 3, 4, 5]乱序import random
li = [1, 2, 3, 4, 5]random.shuffle(li)print(li) # [2, 4, 3, 1, 5]反转li = [1, 2, 4, 0]
li.reverse()print(li) # [0, 4, 2, 1]li = ["ss", "yu", "sfj"]
res = li[::-1]print(li, res) # ["ss", "yu", "sfj"] ['sfj', 'yu', 'ss']元组有序的不可变的元素集合,切片和根据索引获得单个元素的方式和列表相同。
表示方法
t = (1,)
t1, t2 = (1, 2), (2, 3, 9, 0)
t = ("abc", [1, 2], 666)
t = ("rity", (18, "nanchang"))
拆包操作
t = (1, 2, 3)
a, b, c = tprint(a, b, c) # 1 2 3字典无序、可变的键值对的集合
表示方式
key不能重复,若有重复,后定义的覆盖前面定义的
key的类型必须是不可变的类型可变类型(列表,字典,可变集合)不可变类型(数值,布尔,字符串,元组)Python的字典是通过哈希(hash)的方式实现的,计算键的哈希值,存储在哈希表中。person = {"name": "rity", "age": 18}print(person, type(person)) # {'name': 'rity', 'age': 18} 'print(person["name"]) # rityprint(person["age"]) # 18d = dict.fromkeys("abc", 666)print(d) # {'a': 666, 'b': 666, 'c':666}添加元素d = {"name": "s1", "age": 18}
d["height"] = 175d["height"] = 180 # 若键已经存在,则会修改原来对应的值print(d) # {'age': 18, 'name': 's1', 'height': 175}
d.update({"year": 1997, "height":180})
删除元素d = {"name": "s1", "age": 18}
del d["name"]
print(d) # {"age": 18}del d["name1"] # KeyError: 'name1'v = d.pop("age")
print(v, d) # 18 {'name': 's1'}res = d.popitem()
print(res) # ('age', 18)d.clear()
print(d) # {}del dprint(d) # 报错获得元素d = {"name":"Rity", "age": 18}
print(d["name"]) # Rity
print(d["height") # 报错,键不存在print(d.get("age")) # 18
print(d.get("height")) # Noneprint(d.get("height", 170) # 170遍历d = {"name":"Rity", "age": 18}
#-------------------------------------ks = d.keys()
print(ks) # dict_values(['Rity', 18])vs = d.values()
print(vs) # dict_keys(['name', 'age'])itms = d.items()
print(itms) #dict_items([('name', 'Rity'), ('age', 18)])#-------------------------------------for x in d.items():
print(k, end=' ') # ('name':'Rity') ("age":18)for k, v in d.items():
print(k, v, sep='-') # name-Rity age-18集合无序的,不可随机访问的,不可重复的元素集合
与数学中的集合类似,可以进行集合的交、并、差、补等操作。
分为可变集合和不可变集合set: 可以进行增、删、改操作frozenset: 创建好之后,无法再做修改。可变集合的表示s = {1, 2, 3, 4}
print(s, type(s)) # {1, 3, 4, 2}s1 = set("abc")
s2 = set([1, 2, 3])print(s1, s2) # {'a', 'b', 'c'} {1, 2, 3}s = {x for x in range(3)}
print(s) # {1, 0, 2}不可变集合fs = frozenset("abc")
print(fs) # frozenset({'a', 'c', 'b'})fs = frozenset(x**2 for x in range(1, 6) if x % 2)
print(fs) # frozenset({1, 25, 9})注意事项创建空集合
s = {} # 实际上构建了一个空字典
s = set() # 空集合集合中的元素必须是可哈希的值(不可变类型)。集合中元素若出现重复,则会被合并成一个。li = {1, 2, 2, 3, 3}
li = list(set(li))print(li) # [1, 2, 3]集合的操作单集合操作
s = {1, 2, 3}#-----------------------------------------s.add(4)
print(s) # {1, 3, 2, 4}#-----------------------------------------s.remove(2)
print(s) # {1, 3}s.discard(2)
print(s) # {1, 3}s.discard(666)print(s) # {1, 3}s.pop(1)
print(s) # {2, 3}s.pop() print(s) # {2}s.pop() print(s) # set() //空集合的意思s.clear()
print(s) # set()#-----------------------------------------for v in s:
print(s, sep=' ') # 1 2 3its = iter(s)
print(next(its)) # 1print(next(its)) # 2print(next(its)) # 3多集合操作intersection(iterable):s1, s2 = {1, 2, 3, 4, 5}, {9, 8, 8, 5, 4}
res = s1.intersection(s2)print(res) # {4, 5}print(s1 & s2) # {4, 5}
intersection_update(iterable)s1, s2 = {1, 2, 3, 4, 5}, {9, 8, 8, 5, 4}
s1.intersection_update(s2)print(s1) # {4, 5}union(iterable):s1, s2 = {1, 2, 3}, {2, 3, 4}
res = s1.union(s2)print(res) # {1, 2, 3, 4}print(s1 | s2) # {1, 2, 3, 4}
update(iterable)s1, s2 = {1, 2, 3}, {2, 3, 4}s1.update(s2)print(s1) # {1, 2, 3, 4}difference(iterable)s1, s2 = {1, 2, 3}, {2, 3, 4}
res = s1.difference(s2)print(res) # {1}print(s1 - s2) # {1}
difference_update(iterable):s1, s2 = {1, 2, 3}, {2, 3, 4}s1.difference_update(s2)print(s1) # {1}判定操作时间日历
time模块
获得当前时间戳
import time
t = time.time()yearSpan = t / (60 60 24 * 365)print(yearSpan) # 48.6441059296045获得时间元组import time
t = time.time()res = localtime(t)print(res) # time.struct_time(tm_year=2018, tm_mon=8, tm_mday=12, tm_hour=10, tm_min=22, tm_sec=4, tm_wday=6, tm_yday=224, tm_isdst=0)获得格式化的时间import time
t = time.time()res = time.ctime(t)print(res) # Sun Aug 12 10:33:58 2018获得格式化的时间字符串res = time.strftime("%y-%m-%d %H:%M:%S", time.localtime())
print(res) # 18-08-12 10:39:28res = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())print(res) # 2018-08-12 10:39:50获取当前cpu时间import time
start = time.clock()
for i in range(0, 10)print(i, end=' ')end = time.clock()print(end - start) # 0.02806393769252448休眠import time
n = 0while True:print(n)time.sleep(1) # 参数单位是秒datetiem模块模块内部有多个类:datetime、date、time。使用时选择合适的类进行操作就行了
获取当天的日期
import datetimet = datetime.datetime.now()print(type(t)) # print(t) # 2018-08-12 11:04:12.982890print(t.year) # 2018print(t.month) # 8计算n天之后的日期import datetimet = datetime.datetime.today()res = t + datetime.timedelta(days=7)print(t, res, sep='|') # 2018-08-12 11:10:31.995501|2018-08-19 11:10:31.995501获得两个日期的时间差import datetimefirst = datetime.datetime(2018, 9, 10, 12, 0, 0)second = datetime.datetime(2018, 10, 1, 0, 0, 0)res = second - firstprint(res) # 20 days, 12:00:00注:喜欢python + qun:839383765 可以获取Python各类免费最新入门学习资料!转载于:https://blog.51cto.com/14186420/2349766