标准数据类型
Python3 中有六个标准的数据类型:
Number(数字)
String(字符串)
List(列表)
Tuple(元组)
Set(集合)
Dictionary(字典)
Python3 的六个标准数据类型中:
不可变数据(3 个):Number(数字)、String(字符串)、Tuple(元组):改变会报错!!!
可变数据(3 个):List(列表)、Dictionary(字典)、Set(集合)。
#Number(数字)Python3 支持 int、float、bool、complex(复数)。
a, b, c, d = 20, 5.5, True, 4+3j
print(type(a),isinstance(a, int), type(b), type(c), type(d))
#String(字符串)
str = 'texttext'
print (str) # 输出字符串
print (str[0:-1]) # 输出第一个到倒数第二个的所有字符
print (str[0]) # 输出字符串第一个字符
print (str[2:5]) # 输出从第三个开始到第五个的字符
print (str[2:]) # 输出从第三个开始的后的所有字符
print (str * 2) # 输出字符串两次,也可以写成 print (2 * str)
print (str + "TEST") # 连接字符串
#使用反斜杠 \ 转义特殊字符
#如果你不想让反斜杠发生转义,可以在字符串前面添加一个 r,表示原始字符串:
print("te\nnxt\n")
print(r"te\nnxt")
#List(列表):列表是写在方括号 [] 之间、用逗号分隔开的元素列表。
list = [ 'abcd', 786 , 2.23, 'text', 70.2 ]
tinylist = [123, 'text']
print (list) # 输出完整列表
print (list[0]) # 输出列表第一个元素
print (list[1:3:1]) # 从第二个开始输出到第三个元素,步长为一
print (list[2:]) # 输出从第三个元素开始的所有元素
print (tinylist * 2) # 输出两次列表
print (list + tinylist) # 连接列表
# 扩展:字符串翻转题
def reverseWords(input):
# 通过空格将字符串分隔符,把各个单词分隔为列表
inputWords = input.split(" ")
# 翻转字符串
# 假设列表 list = [1,2,3,4],
# list[0]=1, list[1]=2 ,而 -1 表示最后一个元素 list[-1]=4 ( 与 list[3]=4 一样)
# inputWords[-1::-1] 有三个参数
# 第一个参数 -1 表示最后一个元素
# 第二个参数为空,表示移动到列表末尾
# 第三个参数为步长,-1 表示逆向
inputWords=inputWords[-1::-1]
# 重新组合字符串
output = ' '.join(inputWords)
return output
if __name__ == "__main__":
input = 'I like python'
rw = reverseWords(input)
print(rw)
#Tuple(元组):元组的元素不能修改。元组写在小括号 () 里,元素之间用逗号隔开。
#元组中的元素类型也可以不相同:
tuple = ( 'abcd', 786 , 2.23, 'python', 70.2 )
tinytuple = (123, 'python')
print (tuple) # 输出完整元组
print (tuple[0]) # 输出元组的第一个元素
print (tuple[1:3]) # 输出从第二个元素开始到第三个元素
print (tuple[2:]) # 输出从第三个元素开始的所有元素
print (tinytuple * 2) # 输出两次元组
print (tuple + tinytuple) # 连接元组
tup1 = () # 空元组
tup2 = (20,) # 一个元素,需要在元素后添加逗号
#Set(集合)
sites = {'Google', 'Taobao', 'python', 'Facebook', 'Zhihu', 'Baidu'}
print(sites) # 输出集合,重复的元素被自动去掉
# 成员测试
if 'python' in sites :
print('python 在集合中')
else :
print('python 不在集合中')
# set可以进行集合运算
a = set('abracadabra')
b = set('alacazam')
print(a) #相同字母不输出,输出集合,重复的元素被自动去掉。
print(a - b) # a 和 b 的差集
print(a | b) # a 和 b 的并集
print(a & b) # a 和 b 的交集
print(a ^ b) # a 和 b 中不同时存在的元素
Dictionary(字典)
字典(dictionary)是Python中另一个非常有用的内置数据类型。
列表是有序的对象集合,字典是无序的对象集合。两者之间的区别在于:
字典当中的元素是通过键来存取的,而不是通过偏移存取。
字典是一种映射类型,字典用 { } 标识,它是一个无序的 键(key) : 值(value) 的集合。
键(key)必须使用不可变类型。
在同一个字典中,键(key)必须是唯一的。
dict = {}
dict['one'] = "1 - 菜鸟教程"
dict[2] = "2 - 菜鸟工具"
print (dict['one']) # 输出键为 'one' 的值
print (dict[2]) # 输出键为 2 的值
tinydict = {'name': 'runoob','code':1, 'site': 'www.runoob.com'}
print (tinydict) # 输出完整的字典
print (tinydict.keys()) # 输出所有键
print (tinydict.values()) # 输出所有值
构造函数 dict() 可以直接从键值对序列中构建字典如下:
dict([('Runoob', 1), ('Google', 2), ('Taobao', 3)])
{'Runoob': 1, 'Google': 2, 'Taobao': 3}
>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}
>>> dict(Runoob=1, Google=2, Taobao=3)
{'Runoob': 1, 'Google': 2, 'Taobao': 3}
#==============================================================================
# 字符串
#==============================================================================
var1 = 'Hello World!'
print ("已更新字符串 : ", var1[:6] + 'Runoob!')
print (r'\n')
print (R'\n')
#==============================================================================
#python 3.6
# name = 'Runoob'
# print(f'Hello {name}') # 替换变量
#==============================================================================
print ("我叫 %s 今年 %d 岁!" % ('小明', 10))
#python三引号允许一个字符串跨多行,字符串中可以包含换行符、制表符以及其他特殊字符
para_str = """这是一个多行字符串的实例
多行字符串可以使用制表符
TAB ( \t )。
也可以使用换行符 [ \n ]。
"""
print (para_str)
#==============================================================================
# 列表list
#==============================================================================
list1 = ['Google', 'Runoob', 'Taobao']
list1.append('Baidu')
print ("更新后的列表 : ", list1)
for x in [1, 2, 3]: print(x, end=" ")
squares = [1, 4, 9, 16, 25]
squares += [36, 49, 64, 81, 100]
print(squares)
#==============================================================================
# 元组Tulpe
#==============================================================================
tup1 = ('Google', 'Runoob', 1997, 2000)
tup2 = (1, 2, 3, 4, 5 )
tup3 = "a", "b", "c", "d" # 不需要括号也可以
print(type(tup3))
list1= ['Google', 'Taobao', 'Runoob', 'Baidu']
tuple1=tuple(list1)
print(tuple1)
print("内存地址:",id(tuple1))
#==============================================================================
# 字典dict
#==============================================================================
dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8 # 更新 Age
dict['School'] = "菜鸟教程" # 添加信息
print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])
dict = {'Name': 'Runoob', 'Age': 7, 'Name': '小菜鸟'}
#不允许同一个键出现两次。创建时如果同一个键被赋值两次,后一个值会被记住
print ("dict['Name']: ", dict['Name'])
#==============================================================================
# 集合(set)是一个无序的不重复元素序列。
# 可以使用大括号 { } 或者 set() 函数创建集合
# 注意:创建一个空集合必须用 set() 而不是 { },因为 { } 是用来创建一个空字典。
# 创建格式:
# parame = {value01,value02,...}
# 或者
# set(value)
#==============================================================================
basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
print(basket) # 这里演示的是去重功能
#将元素 x 添加到集合 s 中,如果元素已存在,则不进行任何操作。
thisset = set(("Google", "Runoob", "Taobao"))
thisset.add("Facebook")
print(thisset)
thisset.update({1,3})
print(thisset)
#{1, 3, 'Google', 'Taobao', 'Runoob'}
thisset.update([1,4],[5,6])
print(thisset)
#{1, 3, 4, 5, 6, 'Google', 'Taobao', 'Runoob'}
list0=['Tom','Rose']
list1=[1,2,3,4]
list0.append("Rose")
print(list0)
list1.insert(1,"老师")
print(list1)
# 1 2 3 迭代
for x in (1, 2, 3): print (x,)
#字典
dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
key = dict.keys()
item = dict.items()
print(key)
print(item)
for key,value in dict.items():
print(key,value)
#集合set
thisset = set(("Google", "Runoob", "Taobao", "Facebook"))
#enumerate()返回两个值(值+值的索引)
for i,j in enumerate(thisset):
print(i,j)
# 元组、字典、集合、推导式(数据结构阶段)
# 数据结构~数组,栈,队列,三元组,邻接矩阵,线性表,树,图等
# 数据结构---带结构(逻辑上的关系)的数据
# 元组---数据不可发生改变
num_list = [10, 20, 30]
num_list[0] = 100
print(num_list)
# 元组的定义 使用()
tupple1 = (10, 20, 30)
# print(type(tupple1)) #turtle
print(tupple1)
tupple12 = (10, "x+", 30)
# tupple12[0] = 20 #元组中的元素不可以修改
print(tupple12)
# 查
# 案例1:访问元组中的某个元素
nums = (10, 20, 30, 20, 30, 20)
print(nums[0])
# 查找某个元素在元组中出现的位置,
# 存在则返回索引下标,不存在则直接报错
print(nums.index(20))
# 统计某个元素在元组中出现的次数
print("个数:",nums.count(20))
# len()方法主要就是求数据序列的长度,字符串、列表、元组
print(len(nums))
# ==================字典===============
# 空字典
dict = {}
print(type(dict))
# 有数据字典
dict2 = {"name": "Tom", "age":20, "gender":"男"}
print(dict2)
# 字典的增加
num2 = [1,2,3]
num2.append(4)
dict = {}
# 向字典添加元素
dict["name"] = "Cat"
dict["age"] = 28
print(dict)
# list--删除操作(del clear)
dict = {"name": "Tom", "age":20, "gender":"男"}
del dict["name"]
print(dict)
# clear 删库跑路(先备份)
dict.clear()
print(dict)
dict = {"name": "Tom", "age":20, "gender":"男"}
dict["gender"] = "女"
print(dict)
#
cat = {'name':'Tom', 'age':5, 'address':'美国纽约'}
# 案例1:使用get获取字典中某个key的value值
namevlue = cat.values()
print(namevlue)
# 案例2:提取person字典中的所有key
name = cat.keys()
print(name)
# 案例3:提取person字典中的所有value值
item = cat.items()
print(item)
# 字典的遍历
for key, value in cat.items():
print(key,value)
# 集合
s1 = {10, 20, 30, 40, 50}
print(s1,type(s1))
# 空集合
# s2 = {} #空集合不推荐这种方法定义
# print(type(s2))
s3 = set()
print(type(s3))
# 增删改查
students = set()
# 添加
students.add('xj')
students.add('yg')
print(students)
# update()方法
list1 = ['刘备', '关羽', '赵云']
students.update(list1)
print(students)
students = set()
students.add('刘德华')
students.add('黎明')
# 使用update新增元素
students.update('蔡徐坤')
print(students)
# 集合的删操作
# 1、定义一个集合
products = {'萝卜', '白菜', '水蜜桃', '奥利奥', '西红柿', '凤梨'}
# 2、使用remove方法删除白菜这个元素
products.remove('白菜')
print(products)
# 3、使用discard(丢弃)方法删除未知元素
products.discard('玉米')
print(products)
# 4、使用pop方法随机删除某个元素
del_product = products.pop()
print(del_product)
# 定义一个set集合
s1 = {'帅', '英标', '高源'}
# 判断刘帅是否在s1集合中
if '帅' in s1:
print('帅在s1集合中')
else:
print('帅没有出现在s1集合中')
# 1、+加号,代表两个序列之间的连接与整合
str1 = 'hello'
str2 = 'world'
print(str1 + str2)
# # 2、定义两个列表,对其数据进行整合
list1 = ['刘备', '关羽']
list2 = ['诸葛亮', '赵云']
print(list1 + list2)
# # 3、定义两个元组,对其数据进行整合
tuple1 = (10, 20)
tuple2 = (30, 40)
print(tuple1 + tuple2)
# 1、字符串与乘号的关系
print('-' * 40)
print('传智教育Python管理系统V1.0')
print('-' * 40)
# # 2、列表与乘号的关系
list1 = ['*']
print(list1 * 10)
# # 3、元组与乘号的关系
tuple1 = (10, )
print(tuple1 * 10)
# enumerate() 返回两个值 ( 值 与 值所对应的索引)
list1 = [10, 20, 30, 40, 50]
for i,j in enumerate(list1):
print(i,j)
# 1、定义元组类型的序列
tuple1 = (10, 20, 30)
print(list(tuple1))
# # 2、定义一个集合类型的序列
set1 = {'a', 'b', 'c', 'd'}
print(list(set1))
# # 3、定义一个字典
dict1 = {'name':'刘备', 'age':18, 'address':'蜀中'}
print(list(dict1))