用户搜索需求:了解如何购买瑞迪汽车,

python入门系列:Python数据类型

整数

# 二进制n1 = 0b1010# 八进制n2 = 0o567# 十六进制n3 = 0xfdc2

浮点数

# 一般形式n1 = 3.14# 科学计数法n2, n3 = 3.2e6, 1.2e-3

简单数学函数

内建函数

  • abs(num):
# 返回数的绝对值n1, n2, n3 = 1, 0, -1print(abs(n1), abs(n2), abs(n3)) # 1 0 1
  • max(num)min(num):
# 参数不定长n1, n2, n3, n4 = 1, 2, 3, 4print(max(n1, n2), min(n2, n3 , n4)) # 2 4# 接收可迭代对象li = <1, 2, 3, 4>print(max(li)) # 4
  • round(num, n>):
# 四舍五入# n表示四舍五入的小数位数,不写默认是0(取整)pi = 3.14159print(round(pi)) # 3print(round(pi, 3)) #3.142

math模块中的函数

  • ceil():
# 用来向上取整import mathpi = 3.14159print(round(pi)) # 3print(math.ceil(pi)) # 4print(round(pi + 0.5)) # 可以替代ceil()
  • floor():
# 用来向下取整import mathx = 3.678print(round(x)) # 4print(math.floor(x)) # 3print(floor(x - 0.5)) # 可以替代floor()
  • sqrt():
# 平方根运算import mathprint(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()函数一样# 相当于random.choice(<2, 4, 6, 8>)

三角函数

import mathangle = 1 / 6 * math.pi # 30°, pi/6res1 = math.sin(angle) # 接收弧度值angle = math.radians(30) # 将角度值转换为弧度值res1 = math.cos(angle)

布尔类型

是 int 的子类型,计算时会自动转换为 int

# True = 1, False = 0# 可以与整数进行运算print(2 + True) # 3print(1 + False) # 1

是一种单独的类型

flag, tag = True, False

可以当作判定条件使用

if True: # todo

字符串

字符串表示方式

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 all# 字符串的跨行表示str = "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>) # dprint(str<-1>) # g# 获得字符串片段# str# 默认值:start=0, end=len(str), step=1# 获得范围 ) # abcdefgprint(str<0:len(str):1>) # agcdefgprint(str<::2>) #acegprint(str<::-1>) #gfedcba
  • 函数操作
  • len():
# 可用于所有可迭代对象# 计算字符串中字符的个数name1, name2 = "rity", "瑞迪"print(len(name1), len(name2)) # 4 2
  • find():
# 查找子串的索引# find(substr, start, end)# 默认值:start=0, end=len(str)str = "abcdabefg"print(str.find("ab")) # 0print(str.find("ab", 1)) # 4print(str.find("xy")) # -1
  • count():
# 计算子字符串出现的个数# count(sub, start, end)# 默认值:start=0, end=len(str)str = "abcda"print(str.count("a")) # 2print(str.count("a", 2) # 1print(str.count("x")) # 0
  • replace():
# 用给定的新字符串替换旧的字符串# replace(old, new, count)# 默认值:count(省略),全部替换str = "abacad"print(str.replace("a", "A")) #AbAcAdprint(str.replace("a", "A", 2)) #AbAcadprint(str) # abacad
  • ljust() 和 rjust():
# 对字符串进行长度调整(扩长)# ljust(width, fillchar)# width:要扩展到的长度,fillchar:填充的字符str = "abc"print(str.ljust(6, "x")) # abcxxxprint(str.rjust(6, "x")) # xxxabcprint(str) # abc
  • lstrip() 和 rstrip() 和 strip()
# 移除字符串指定位置的字符# lstrip(str)# 默认值:str是空字符集name = "xi am rity ."print(name.lstrip("ix")) # | am rity .|print(name.rstrip(". ") # |xi am rity|print(name.strip("ix.")) # | am rity |
  • split():
# 将父字符串分割成几个子字符串# split(sep=None, maxsplit=-1)# sep:要分割的字符,maxsplit:最大分割次数# 默认值:maxsplit(省略),全部分解# 返回字符串列表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():
# 把整个字符串分三部分# partition(sep)# 从左往右找# 返回一个元组(分隔符左侧, 分隔符, 分隔符右侧)pi = 3.14159res1 = pi.partition(".")res2 = pi.partition("-")print(res1) # ('3', '.', '14159')print(res2) # ('3.14159', '', '')
  • join():
# 用指定的字符串,对可迭代参数进行拼接,返回字符串# "xx".join(iterable)# 与split()的作用相反li = <"137", "9878", "0098">res1 = "-".join(li)res2 = "".join(li)print(res1) # 137-9878-0098print(res2) # 13798780098
  • isalpha(), 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 False
  • startswith() 和 endswith()
# 是否以某个前缀开头/结尾,范围 

列表

有序可变元素的集合

表示方式

# 元素类型单一li = <"a", "b", "c"> # 多种类型的元素li = <"a", "b", 1, 2, True> # 列表可以相互嵌套li = <<1, 2, 3>, 2, True, "hehe"> # list()函数,参数为可迭代对象li = list(range(1, 4)) # <1, 2, 3>li = list("abc") # ('a', 'b', 'c') # 列表推导nums = <1, 2, 3, 4, 5>li = 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># del用来删除所引用的对象
  • pop():
# 移除并返回列表中指定索引的元素# pop(index)# 默认值:index(不写),删除返回最后一个nums = <1, 2, 3>res = nums.pop()print(nums, res) # <1, 2> 3
  • remove():
# 移除列表中指定的元素# remove(obj)# 若元素不存在会报错,若有多个元素,删除最左边的那个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():
# 获得元素所在的索引值,查找范围:idx = li.index(34)print(idx) # 1
  • count():
# 获得其中某个元素的个数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 += 1# 建立索引列表idxList = list(range(0, len(val)))for idx in idxList: print(idx, val)# 利用枚举对象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)
  • 排序
# ----------------------------------------# 使用内建函数 sorted(),可以对所有可迭代对象排序# sorted(itrearble, key=None, reverse=False)# 不改变原对象,以列表的形式返回处理后的结果# 默认按照升序排列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)># -----------------------------------------# 使用列表的对象方法# 直接修改原对象# 参数列表与 sorted()相同li = <1, 3, 5, 2, 0>li.sort()print(li) # <0, 1, 2, 3, 4, 5>
  • 乱序
# 打乱列表中元素的顺序# 直接修改原对象import randomli = <1, 2, 3, 4, 5>random.shuffle(li)print(li) # <2, 4, 3, 1, 5>
  • 反转
# 使用reverse()直接修改原对象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"))# tuple()函数,用法与list()相同

拆包操作

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}# 使用 d0.update(d1)# 将两个字典合并,若旧字典中有对应的 key,则更新;否则添加d.update({"year": 1997, "height":180})

删除元素

d = {"name": "s1", "age": 18}# 使用 del直接删除键值# 删除不存在的键值对会直接报错del d<"name"> print(d) # {"age": 18}del d<"name1"> # KeyError: 'name1'# dic.pop()# 删除指定的键值对,并返回对应的值# 删除不存在的键值对会直接报错v = d.pop("age")print(v, d) # 18 {'name': 's1'}# dic.popitem()# 删除按升序排序后的第一个键值对,并以元组的形式返回键值对# 字典为空报错res = d.popitem()print(res) # ('age', 18)# dic.clear()# 清空字典,空字典,不是未定义的对象d.clear()print(d) # {}del dprint(d) # 报错

获得元素

d = {"name":"Rity", "age": 18}# 下标访问print(d<"name">) # Rityprint(d<"height") # 报错,键不存在# dic.get(key, default)# 键不存在不会报错,default是键不存在时的返回值,默认为 Noneprint(d.get("age")) # 18print(d.get("height")) # Noneprint(d.get("height", 170) # 170

遍历

d = {"name":"Rity", "age": 18}#-------------------------------------# 下面三种方法返回的是一个 Dictionary view objects, 虽然以列表的形式展现,但严格来说不是列表# 不支持索引访问,但可以使用 list()来转换成普通的列表对象# 特点:当字典被修改后,以下 ks, vs, itms会同步修改# 获取所有的键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 in# 若直接遍历字典,得到的是它的键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} # set(Iterable)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}

不可变集合

# frozenset(iterable)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}#-----------------------------------------# 新增元素# 1.集合可变 2.新增元素可哈希s.add(4)print(s) # {1, 3, 2, 4}#-----------------------------------------# 删除元素# 1.remove(element)# 删除指定的元素,若无该元素,报错s.remove(2)print(s) # {1, 3}# 2.discard(element)# 删除指定的元素,若无该元素,passs.discard(2)print(s) # {1, 3}s.discard(666)print(s) # {1, 3}# 3.pop(element)# 删除并返回指定元素,若无该元素,报错# 省略 element,不指定删除元素,进行随机删除;集合为空,报错s.pop(1)print(s) # {2, 3}s.pop() print(s) # {2}s.pop() print(s) # set() //空集合的意思# 4.clear()# 清空集合,集合依然存在s.clear()print(s) # set()#-----------------------------------------# 遍历集合# 1.for infor v in s: print(s, sep=' ') # 1 2 3 # 2.迭代器its = 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}# s1也可以是frozenset,返回结果也是frozenset# 可以使用逻辑运算符来完成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}
  • 判定操作
# isdisjoint() 两个集合是否不相交# isuperset() 一个集合是否包含另一个集合# issubset() 一个集合是否包含于另一个集合

时间日历

time模块

  • 获得当前时间戳
# 获得从 1970年1月1日到现在的时间秒数import timet = time.time()yearSpan = t / (60 * 60 * 24 * 365)print(yearSpan) # 48.6441059296045
  • 获得时间元组
# 根据所给的时间戳,返回当时的时间信息import timet = 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 timet = time.time()res = time.ctime(t)print(res) # Sun Aug 12 10:33:58 2018
  • 获得格式化的时间字符串
# time.strftime(格式字符串, 时间元组)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# IDLE环境测试start = time.clock()for i in range(0, 10) print(i, end=' ')end = time.clock()print(end - start) # 0.02806393769252448
  • 休眠
# 线程休眠# 每隔一秒打印一个数字import timen = 0while True: print(n) time.sleep(1) # 参数单位是秒

datetiem模块

模块内部有多个datetimedatetime。使用时选择合适的类进行操作就行了

  • 获取当天的日期
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各类免费最新入门学习资料!

2024-03-03

后面没有了,返回>>电动车百科