天天看点

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]
           

继续阅读