首先明確:
1、列表list是一種數(shù)據(jù)結(jié)構(gòu)
2、list可以進行的操作:索引,取部分(也叫切片),加,乘,檢查成員
3、列表的數(shù)據(jù)項不需要具有相同的類型
具體的操作:
1、創(chuàng)建列表??
?list1=[1,2,3,5,7]? ? ??
?list2=['a','b','d']
2、查看列表的值??
?print(list) :相當(dāng)于遍歷整個列表? ? ??
list[0] 訪問列表的第一個元素
list.count(1):某個元素在列表中出現(xiàn)的次數(shù)? ?
list.index(1):元素出現(xiàn)的角標(biāo)
3、添加新元素? ?
list.append()? 在列表的末尾加入元素
ist.insert(n, x):在第n個位置插入x
?list1.extend(list2)? :把第二個列表接在第一個列表后面
4、切片? ?
list[m,n]? ? 取列表的第m個元素到n之前的元素,取不到n
list[:n]? ? ? ?取列表從頭開始到n之前的元素,取不到n
list[m:]? ? ? 取列表從m開始到結(jié)尾,包括結(jié)尾的元素
list[m:n:x]? ? 取列表第m到第n之前的數(shù)據(jù),步長為x
5、排序(列表的排序針對同類型元素)
list.reverse()? 將列表反轉(zhuǎn)
list.sort()? ? ? ? 列表按照升序排列
list.sort(reverse==True)? ? 列表按照降序排列
6、刪除元素
list.pop() :刪除最后一個元素,如果括號內(nèi)有值則刪除那個下表下的元素
list.remove(x) :刪除x,如果有多個相同元素刪除第一個
7、列表的一些計算?
len(list) :列表的長度
max(list) :列表中的最大值? ? ? ? ? ? ? ? ? ? ? min(list):列表中的最小值
一個小題:
給定一個整數(shù)數(shù)組?nums和一個目標(biāo)值?target,請你在該數(shù)組中找出和為目標(biāo)值的那?兩個?整數(shù),并返回他們的數(shù)組下標(biāo)。
解題:
class Solution:
? ? def twoSum(self, nums: List[int], target: int) -> List[int]:
? ? ? ? x = len(nums)
? ? ? ? for i in range(0,x):
? ? ? ? ? ? for j in range(i+1,x):
? ? ? ? ? ? ? ? if nums[i]+nums[j]== target:
? ? ? ? ? ? ? ? ? ? return [i,j]