4、python数据类型之列表(list)

列表
列表常见操作
1、索引取值

name_list = ['wang','zhou','li','hu','wu','zhao']
print(name_list[0])
print(name_list[-1])

2、列表切片

#将列表中第一个到第二元素切片出来,形成一个子列表
name_list = ['wang','zhou','li','hu','wu','zhao']
print(name_list[1:3])

3、获取列表的长度

name_list = ['wang','zhou','li','hu','wu','zhao']
#h获取长度
print(len(name_list))
#输出所有的元素
print(name_list[0:len(name_list)])

4、for循环打印出列表的所有元素

name_list = ['wang','zhou','li','hu','wu','zhao']
for i in name_list:
    print(i)

5、删除列表指定位置元素

name_list = ['wang','zhou','li','hu','wu','zhao']
#删除第一个元素
name_list = ['wang','zhou','li','hu','wu','zhao']
del name_list[1]
print(name_list)
#删除第0个到第一个元素
name_list = ['wang','zhou','li','hu','wu','zhao']
del name_list[0:2]
print(name_list)

列表方法

name_list = ['wang','zhou','li','hu','wu','zhao']
#获取列表的所有方法,包括内置方法
print(dir(name_list))
#外部方法
['append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

append

#在列表尾部追加元素
name_list = ['wang','zhou','li','hu','wu','zhao']
name_list.append('hehe')
print(name_list)

 clear

#将列表中元素清空,形成一个空列表
name_list = ['wang','zhou','li','hu','wu','zhao']
name_list.clear()
print(name_list)

 count

#统计列表中某一个元素出现的次数
name_list = ['wang','zhou','li','hu','wu','zhao']
num=name_list.count('li')
print(num)

 extend(凡是可以迭代的都可以extend到列表中)

#将一个列表全部元素追加到另一个列表中(也可以将字符串、元组、字典追加上去)
name_list = ['wang','zhou','li','hu','wu','zhao']
num_list = [1,2,34,56,32]
name_list.extend(num_list)
print(name_list)

index

#h获取列表中某个元素的索引
name_list = ['wang','zhou','li','hu','wu','zhao']
print(name_list.index('wang'))

 insert

#在列表中某个位置插入一个元素
name_list = ['wang','zhou','li','hu','wu','zhao']
name_list.insert(3,'good')
print(name_list)
print(name_list.index('good'))

 pop

#删除列表中最后一个元素,且可以将该元素作为一个字符串赋值给一个变量
name_list = ['wang','zhou','li','hu','wu','zhao']
a=name_list.pop()
print(name_list)
print(a)

 remove

#移除列表中指定元素
name_list = ['wang','zhou','li','hu','wu','zhao']
name_list.remove('34')
print(name_list)

 reverse

#将列表中所有元素翻转过来
name_list = ['wang','zhou','li','hu','wu','zhao']
name_list.reverse()
print(name_list)

sort

#列表元素排序
num =[23,123,45,12,456,323,1,34]
num.sort()
print(num)
posted @ 2018-01-11 23:29  wclwcw  阅读(364)  评论(0编辑  收藏  举报