python基础篇--List(列表)

List(列表)
特点:列表的元组不需要具有相同的类型,列表每个元组都有它的位置(index),第一个为0,第二个为1,以此类推。
标识:[]
例子:list2 = [1, 2, 3]

访问列表:
list2 = [1, 2, 3, 4, 5]
list3 = ['dong', 'you', 'yuan', '1234']
print list2[0]
print list3[1:3]    # 下标1到3(不包括3)
# 输出结果
# 1
# ['you', 'yuan']

修改列表:
list2 = [1, 2, 3, 4, 5]
print list2
list2[2] = 345
print list2
# 输出结果
# [1, 2, 3, 4, 5]
# [1, 2, 345, 4, 5]

删除列表元素:
list2 = [1, 2, 3, 4, 5]
del list2[2]
print list2
# 输出结果
# [1, 2, 4, 5]

列表操作符:
list_01 = [1, 2, 3]
list_02 = [5, 6, 7, 8]
print len(list_01)
list_03 = list_01 + list_02
print list_03
print ['8'] * 4
print 3 in list_01
for i in list_01:   # 迭代访问
    print i
# 输出结果
# 3
# [1, 2, 3, 5, 6, 7, 8]
# ['8', '8', '8', '8']
# True
# 1
# 2
# 3

列表截取:
list2 = [1, 2, 3, 4, 5, 6]
print list2[2]
print list2[-2]
print list2[-2:-1]
print list2[1:]
print list2[:-1]
# 输出结果
# 3
# 5
# [5]
# [2, 3, 4, 5, 6]
# [1, 2, 3, 4, 5]

内置函数:
cmp(list2, list3) : 比较两个列表的元素
len(list2):列表元素个数
max(list2):返回列表元素最大值
min(list2):返回列表元素最小值
list(tuple):将元组转换为列表
列表方法:
list2.append(obj):在列表末尾添加新对象
list2.count(obj):统计某个元素在列表中出现的次数
list2.extend(list3):在列表末尾一次性追加另一个列表的多个值
list2.index(obj):从列表中找出某个值第一个匹配项的索引位置
list2.insert(index, obj):在列表的index位置插入一个对象
list2.pop(index):删除下标为index的元素,默认为最后一个
list2.remove(obj):移除列表中某个值的第一个匹配项
list2.reverse(obj):反向排序列表中元素(从大到小)
list2.sort():对列表进行排序(从小到大)

enumerate函数:
for index, value in enumerate([1, 3, 6, 8, 3]):
    print index, value
# 输出结果
# 1 3
# 2 6
# 3 8
# 4 3

扩展:
list2 = [1, 2, 3, 2, 4, 5, 1, 6, 4] 去掉当中的重复的元素。
答:
list2 = [1, 2, 3, 2, 4, 5, 1, 6, 4]
print list(set(list2))
# 输出结果
# [1, 2, 3, 4, 5, 6]






你可能感兴趣的:(python基础篇--List(列表))