1、字符串
Python 不支持单字符类型,单字符在 Python 中也是作为一个字符串使用。
Python 访问子字符串,可以使用方括号来截取字符串。
#字符串
string1 = 'hello world '
string2 = "i like dji"
print("6、",string1)
print("7、",string2[1:6])
print("8、",string2[0])
print("9、",string1+string2) #字符串连接
print("10、","h" in string1) #成员运算符
print("11、","i" in string1) #成员运算符
print("12、","i" not in string1) #成员运算符
输出结果:
在需要在字符中使用特殊字符时,python 用反斜杠 \ 转义字符。
2、列表
列表是Python中最基本的数据结构。列表中的每个元素都分配一个索引,第一个索引是0,第二个索引是1,依此类推。
创建一个列表,要把逗号分隔的不同的数据项使用方括号括起来,列表的数据项不需要具有相同的类型
#列表
list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5 ]
list3 = ["a", "b", "c", "d"]
#访问列表中的值
print("13、",list1[1:3])#左闭右开
print("14、",list1[0])
list = [] ## 空列表
list.append('Google') ## 使用 append() 添加元素
list.append('Runoob')
print("15、",list)
del list[1] # 删除列表元素
print("16、",list)
#列表截取
print("17、",list1[1:])#从第二个元素开始到结束
print("18、",list1[-2])#倒数第二个元素
函数 | 作用 |
---|---|
cmp(list1,list2) | 比较两列表的元素 |
len(list) | 列表元素个数 |
max(list) | 返回列表元素最大值 |
min(list) | 返回列表元素最小值 |
list.count(obj) | 统计某个元素在列表中出现的次数 |
list.extend(seq) | 在列表末尾一次性追加另一个序列中的多个值 |
list.index(obj) | 从列表中找出某个值第一个匹配项的索引位置 |
list.pop([index=-1]) | 移除列表中的一个元素(默认最后一个元素),并且返回该元素的值 |
list.insert(index, obj) | 将对象插入列表 |
list.reverse() | 反向列表中元素 |
list.reverse() | 对原列表进行排序 |
3、元组
Python的元组与列表类似,不同之处在于元组的元素不能修改
#元组
tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5 )
tup3 = "a", "b", "c", "d"
tup4 = ()#空元组
print("19、",tup1[0])
print("20、",tup2[1:5])
print("21、",tup1+tup2)
print("22、",tup3)
del tup3
print("23、",tup3)
元组索引,截取
因为元组也是一个序列,所以我们可以访问元组中的指定位置的元素,也可以截取索引中的一段元素,方法同序列,不再赘述。
4、字典
字典是一种可变容器模型,且可存储任意类型对象。
字典的每个键值 key=>value 对用冒号 : 分割,每个键值对之间用逗号 , 分割,整个字典包括在花括号 {} 中 ,键一般是唯一的,如果重复,最后的一个键值对会替换前面的,值不需要唯一,类似java中的hashmap。
#字典
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict1 = { 'abc': 456 }
dict2 = { 'abc': 123, 98.6: 37 }
print("24、dict['Name']: ", dict['Name'])
print("25、dict['Age']: ", dict['Age'])
dict['Age'] = 8 # 更新
dict['School'] = "RUNOOB" # 添加
print("26、dict['Age']: ", dict['Age'])
print("27、dict['School']: ", dict['School'])
del dict['Name'] # 删除键是'Name'的条目
字典键的特性
1、不允许同一个键出现两次。创建时如果同一个键被赋值两次,后一个值会被记住
2、键必须不可变,所以可以用数字,字符串或元组充当,所以用列表就不行
函数及方法 | 作用 |
---|---|
cmp(dict1, dict2) | 计算字典元素个数,即键的总数 |
len(dict) | 删除字典内所有元素 |
str(dict) | 输出字典可打印的字符串表示 |
type(variable) | 返回输入的变量类型,如果变量是字典就返回字典类型 |
dict.clear() | 删除字典内所有元素 |
dict.copy() | 返回一个字典的浅复制 |
dict.fromkeys(seq[, val]) | 创建一个新字典,以序列 seq 中元素做字典的键,val 为字典所有键对应的初始值 |
dict.get(key, default=None) | 返回指定键的值,如果值不在字典中返回default值 |
dict.items() | 以列表返回可遍历的(键, 值) 元组数组 |
dict.update(dict2) | 把字典dict2的键/值对更新到dict里 |
popitem() | 返回并删除字典中的最后一对键和值 |