Python 操作列表

2022-08-24 06:00:19 字數 2432 閱讀 3142

1 遍歷列表元素

colors = ["

red","

blue

","yellow

","orange

","white

","pink

","brown"]

for color in

colors :

print(color)

2 使用range()建立數值列表

#

使用range建立數值列表

numbers = list(range(1, 11)) #

range不包括最後乙個值

print

(numbers)

#指定步長,可建立基數或者偶數數值列表

numbers = list(range(2, 11, 2))

print

(numbers)

numbers = list(range(1, 11, 2))

print

(numbers)

#使用**(乘方)建立乘方列表

squares =

for value in range(1, 11):

print(squares)

3 數值列表中最大值,最小值

squares =

for value in range(1, 11):

print

(squares)

#列表中最大值

print

(max(squares))

#列表中最小值

print(min(squares))

4 使用列表解析建立列表

squares = [value**2 for value in range(1, 11)]

print

(squares)

#說明:指定乙個表示式(value**2),寫乙個for迴圈,用於給表示式提供值

5 使用列表的一部分(切片)

#

指定第乙個元素索引和最後乙個元素索引+1

colors = ["

red", "

blue

", "

yellow

", "

orange

", "

white

", "

pink

", "

brown"]

print(colors[1:4])

#沒有指定第乙個索引,從列表開頭開始

print(colors[:4])

#沒有指定最後索引,截止到列表最後乙個元素

print(colors[4:])

#擷取列表後3個元素

print(colors[-5:])

#遍歷切片

for color in colors[-3:]:

print(color)

6 複製列表

#

如果單純的給乙個變數賦值,並沒有複製列表,兩個變數指向同乙個列表

colors = ["

red", "

blue

", "

yellow

", "

orange

", "

white

", "

pink

", "

brown"]

colors_copy =colors

"green")

print(colors) #

colors列表也發生變化了

#使用切片複製列表

colors_copy =colors[:]

"black")

print

(colors)

print(colors_copy)

7 不可變列表(元組)

#

定義元組,使用圓括號而不是方括號

colors = ("

red", "

blue

", "

yellow

", "

orange

", "

white

", "

pink

", "

brown")

print(colors[1])

#如果修改元組中的元素,將返回型別錯誤資訊

colors[0] = "

black"#

錯誤資訊:typeerror: 'tuple' object does not support item assignment

#但可以給元組變數重新賦值,達到修改元組的目的

colors = ("

red", "

blue")

print(colors)

python列表建立操作 python列表操作

建立列表 sample list a 1,a b python 列表操作 sample list a b 0,1,3 得到列表中的某乙個值 value start sample list 0 end value sample list 1 刪除列表的第乙個值 del sample list 0 在列...

python列表建立操作 python列表操作

列表是最常用的python資料型別,它可以作為乙個方括號內的逗號分隔值出現。列表的資料項不需要具有相同的型別。如 list a b 2,5,1 1 新建列表 stus 建立空列表 stus1 list 建立空列表 print stus print stus1 stus 范冰冰 維達 soon 上述 ...

python 列表操作

list 一種順序儲存結構,序列的一種,列表元素可以是任何型別,類似陣列,引用型別。格式定義 olist 1,str 定義乙個空的list olist 獲取列表元素個數 len olist 刪除乙個列表 del olist 刪除乙個列表元素 del list i 支援 olist1 olist2 列...