老男孩python学习自修【第三天】列表用法

时间:2022-09-19 05:05:57

列表的使用:

list.append(value)  向列表增加元素

list.insert(index, value)  向列表指定元素插入元素

list.extend(newlist)  用新的列表扩展列表

list.remove(value)  删除列表的指定值

del list[index]  删除指定索引的值

list.pop()  删除列表最后一个值

list.reverse()  列表反转

list.sort()  列表元素按ASCII码排序

list.count(value)  统计元素的个数

list[index1:index2]  切片操作(顾头不顾尾)

>>> list = [str(a) for a in range(10)]
>>> print list
[']
>>> list.append(11)
>>> print list
[', 11]
>>> list.insert(1, 20)
>>> print list
[', 11]
>>> list.extend(['aaa', 'bbb'])
>>> print list
[', 11, 'aaa', 'bbb']
>>> list.remove(20)
>>> list
[', 11, 'aaa', 'bbb']
>>> list.pop()
'bbb'
>>> list
[', 11, 'aaa']
>>> list.reverse()
>>> list
[']
>>> list[-5:]
[']

实战:打印列表中所有这个值的索引

get_all_index_for_value.py

#!/usr/bin/env python
# _*_ coding:UTF-8 _*-

list = [3,5,4,5,6,5,5]
index = 0

for i in range(list.count(5)):
        new_index = list.index(5)
        index = index + new_index
        print "is Found at", index
        index = index + 1
        list = list[new_index+1:]

结果:

liudaoqangdeAir:list liudaoqiang$ python get_all_index_for_value.py
is Found at 1
is Found at 3
is Found at 5
is Found at 6

当然还可以使用list.index(value, start, end)来实现如下:

#!/usr/bin/env/python
# _*_ coding:UTF-8 _*_

list = [3,5,4,5,6,5,5]
index = 0
for I in range(count(5)):
    if pos == 0:
        index = list.index(5)
    else:
        index = list.index(5, index+1)
    print "is Found at", index

元组的使用

tuple.count()  统计元组的元素个数

tuple.index(value)  返回指定值的索引

tuple[index1:index2]  切片操作

list(tuple)  将元组转化为列表

tuple(list)  将列表转化为元组