网站建设全部教程,专业企业网站建设公司价格,网络推广运营团队,网站开发实训小结1#xff0c;列表#xff1a;list
可变的数据类型#xff0c;可以被改变#xff0c;可以进行嵌套处理#xff0c;可在一个列表中存储一个序列的项目
指明一个列表的方法是#xff1a;使用方括号
代码示例#xff1a;fruit_list [apple, pear, orange, ba…1列表list
可变的数据类型可以被改变可以进行嵌套处理可在一个列表中存储一个序列的项目
指明一个列表的方法是使用方括号
代码示例fruit_list [apple, pear, orange, banana, watermetton, strawberry] lenrth len(fruit_list)print lenrth6for items infruit_list:
print items,
apple pear orange banana watermetton strawberry fruit_list.append(pawpaw) ###添加一个元素 fruit_list.del(apple) ###列表中删除一个元素不能用.del()而是.remove()
SyntaxError: invalid syntax fruit_list.remove(aple)
Traceback (most recent call last):
File, line 1, in fruit_list.remove(aple)
ValueError: list.remove(x): x notinlist fruit_list.remove(apple)fruit_list.pop()pawpawfruit_list.count(apple) ###.count()函数不是统计列表的长度而是查找列表中某个元素出现的次数Lenlist用于计算列表长度0
print fruit_list
[pear, orange, banana, watermetton, strawberry]
2元组
和列表类似但是元组是不可修改的可以进行嵌套
指明一个元组的方法使用圆括号中间使用“ ”将项目分隔
创建一个元组使用逗号分隔或者使用tuple()函数 eg1,2,3 tuple([1,2,3])
代码示例animal_tuple (fish, snake, wolf,(dog, cat, sheap))len(animal_tuple) ##求解元组的长度41,2,3 ##创建一个元组(1, 2, 3) tuple([1,2,3])
(1, 2, 3)animal_tuple.append(mouse) ##元组是不可修改的
Traceback (most recent call last):
File, line 1, in animal_tuple.append(mouse)
AttributeError:tuple object has no attribute appendanimal_tuple.index(dog) ##嵌套在元组内的元组元素无法检索到
Traceback (most recent call last):
File, line 1, in animal_tuple.index(dog)
ValueError: tuple.index(x): x notintuple animal_tuple.index(fish) ##元组的开始元素的标号是00
3字典
把键和值联系在一起其中键必须是唯一的键和值之间用冒号进行分隔
字典的表示方法使用{}键和值之间用冒号“”隔开项之间用逗号“”隔开
代码示例phonebook_dict {Alice: 23456, Tom:67890, Snowy: 67845} ##创建一个字典phonebook_dict
{Snowy: 67845, Alice: 23456, Tom: 67890} items [(Alice, 23456), (Tom,67890), (Snowy, 67845)] ##列表转化为字典 items_dict dict(items)items_dict
{Snowy: 67845, Alice: 23456, Tom: 67890}len(items_dict)3change_items {Robin: 55667}items_dict.update(change_items) ##.update()更新字典内容items_dict
{Snowy: 67845, Alice: 23456, Robin: 55667, Tom: 67890}items_dict.items() ##字典转化为列表.items()函数
[(Snowy, 67845), (Alice, 23456), (Robin, 55667), (Tom, 67890)]
4总结
把序列转化为列表.list(seq) [1,2,3,4] .append() .remove() .pop() .index() .count() len()
把序列转化为元组.tuple(seq) (1,2,3,4) .index() .count() len()
把序列转化为字典 .dict(seq) {1 : Snowy, 2:Tom, 3: Alice} .update() .pop() len()
字典转化为列表 items(dict)
PSstring相当于字符元组
array只能存储同种数据类型的数据区别于list相比较list使用的空间更小通过 from array import array 可以使用array模块
zip()是Python的一个内建函数它接受一系列可迭代的对象作为参数将对象中对应的元素打包成一个个tuple元组然后返回由这些tuples组成的list列表
code:a [1, 2] b [a, c, d]zip(a,b)
[(1, a), (2, c)] zip(*zip(a,b))
[(1, 2), (a, c)] a [[1,2,3],[4,5,6],[7,8,9]]zip(a)
[([1, 2, 3],), ([4, 5, 6],), ([7, 8, 9],)] print [row[0] for row ina]
[1, 4, 7] zip(*a)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
(*)操作符与zip函数配合可以实现与zip相反的功能即将合并的序列拆成多个tuple。