天天看點

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]
           

繼續閱讀