python 列表操作 及 使用方法

1.操作的类型

concatenation + Combine sequences together
repetition * Concatenate a repeated number of times
membership in Ask whether an item is in a sequence
length len Ask the number of items in the sequence
slicing [ : ] Extract a part of a sequence

‘+’    : 将两个列结合在一起

a = [1, 2, 3]
b = [4, 5, 8]
print a +b
输出:[1, 2, 3, 4, 5, 8]

      ‘*’  : 即 重复


>>> myList = [0] * 6
>>> myList
[0, 0, 0, 0, 0, 0]
in’ :判断 是否是其的子集

a = [(1, 2),3]
if (1,2) in a:
    print a
'len()': 返回对象(字符、列表、元组等)长度或项目个数

>>>str = "runoob"
>>> len(str)             # 字符串长度
6
>>> l = [1,2,3,4,5]
>>> len(l)               # 列表元素个数
5
[ : ]’ :切片操作包括一个开始下标,一个结束下标,和一个步长(ps:默认值就是集合的开始下标,集合的最后一个元素下标,与步长为1)

>>> L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']
>>> L[0:3]  # 取头三个元素
['Michael', 'Sarah', 'Tracy']
>>> L[-2:]     #从倒数第二个值开始取值
['Bob', 'Jack']
>>> L[-2:-1]  #取倒数第二个值  ,最后一个值的下标为 -1,依次往前类推 -2 ,-3...
['Bob']
 

2.list的使用(ps:  下表 i 表示索引位置,  item 表示要操作的对象)

append alist.append(item) 在list末尾添加一个新的item
insert alist.insert(i,item) 将指定对象插入列表的指定位置。
pop alist.pop() Removes and returns the last item in a list
pop alist.pop(i) Removes and returns the ith item in a list
sort alist.sort() Modifies a list to be sorted
reverse alist.reverse() Modifies a list to be in reverse order
del del alist[i] Deletes the item in the ith position
index alist.index(item) Returns the index of the first occurrence of item
count alist.count(item) Returns the number of occurrences of item
remove alist.remove(item) Removes the first occurrence of item

myList = [1024, 3, True, 6.5]
myList.append(False)
print(myList)  # [1024, 3, True, 6.5, False]
myList.insert(2,4.5)
print(myList)  #[1024, 3, 4.5, True, 6.5, False]
print(myList.pop())  # False
print(myList) #[1024, 3, 4.5, True, 6.5]
print(myList.pop(1)) # 3
print(myList) # [1024, 4.5, True, 6.5]
myList.pop(2)
print(myList) # [1024, 4.5, 6.5]
myList.sort()
print(myList) # [4.5, 6.5, 1024]
myList.reverse()
print(myList) # [1024, 6.5, 4.5]
print(myList.count(6.5)) # 1
print(myList.index(4.5)) # 2
myList.remove(6.5)
print(myList) # [1024, 4.5]
del myList[0]
print(myList)  # [4.5]





  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值