python之列表

列表

向列表添加元素

append()

number = [1 , 2 , 3 , 4 ,5]

number.append(9)

只能在最后添加一个参数

extend()

number.extend([8 , 10])

添加一个列表到另一个列表中

>>> yourlist
['A', 'E', 'G']
>>> mylist
[1, 7, 9, 11, 13, 15, 17, 19, 23]
>>> mylist.extend(yourlist)
>>> mylist
[1, 7, 9, 11, 13, 15, 17, 19, 23, 'A', 'E', 'G']
>>> yourlist
['A', 'E', 'G']

insert()

number.insert(1, 11)

在第二位插入11,可以在任何位置插入参数

删除列表元素

number.pop() #删除最后一个元素

number.pop(i) #删除任意一个元素

删除列表

del(number)

删除指定元素

del(number[i])

删除指定元素

number.remove(3)

修改指定元素

number[0] = 9

切片  顾头不顾尾

>>> mylist
[1, 7, 9, 13, 11, 15, 17, 19]
>>> mylist[1:4]
[7, 9, 13]
>>> mylist[0:2]
[1, 7]
>>> mylist[:3]
[1, 7, 9]
>>> mylist[:]
[1, 7, 9, 13, 11, 15, 17, 19]
>>> mylist[::2]
[1, 9, 11, 17]
>>> mylist[::3]
[1, 13, 17]
>>> mylist[0:-7]
[1]
>>> mylist[-7:-5]
[7, 9]

获取下标

>>> mylist.index(13)
3
>>> print(mylist.index(9))
2

反转

>>> mylist
[1, 7, 9, 13, 11, 15, 17, 19]
>>> mylist.reverse()
>>> mylist
[19, 17, 15, 11, 13, 9, 7, 1]

排序

按照ASCII码

>>> mylist
[1, 7, 9, 23, 11, 13, 15, 17, 19]
>>> mylist.sort()
>>> mylist
[1, 7, 9, 11, 13, 15, 17, 19, 23]

posted @ 2017-08-15 08:31  HK1537  阅读(114)  评论(0编辑  收藏  举报