- 列表 list []
list是一种有序的集合,可以用索引随时添加和删除其中的元素,列表的数据项不需要具有相同的类型
fruit = ['apple','banana','grape']
print(fruit)
#append() 在列表末尾增加元素
fruit.append('melon')
print(fruit)
#insert()在索引位置增加元素
fruit.insert(1,'pear')
print(fruit)
#pop()删除索引位置元素
fruit.pop(1)
print(fruit)
运行结果
['apple', 'banana', 'grape']
['apple', 'banana', 'grape', 'melon']
['apple', 'pear', 'banana', 'grape', 'melon']
['apple', 'banana', 'grape', 'melon']
元组 tuple ()
有序,一旦初始化就不能再改变,可以用索引访问元素。元组中只包含一个元素时,需要在元素后面添加逗号,否则括号会被当作运算符使用:
>>> tup1 = (50,)
>>> type(tup1)
<class 'tuple'>
>>> tup2 = (50)
>>> type(tup2)
<class 'int'>
- 循环
循环有两种:一种是for…in 循环,依次把list或tuple中的每个元素迭代出来,如:
= ['Alice','Bob','Tracy']
for name in L:
print('hello,%s'%name)
运行结果
hello,Alice
hello,Bob
hello,Tracy
第二种循环是while循环,只要条件满足,就不断循环,条件不满足时退出循环
break退出循环,continue退出当前循环
- 字典directory {}
使用键-值(key-value)存储,具有极快的查找速度
>>> d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
>>> d['Michael']
95
dict的key必须是不可变对象,如字符串,元组等,列表就不行