1. 程式人生 > >Python 之列表

Python 之列表

1.基本操作

#輸出
color=['red','green','purple','blue']
print(color)

#索引輸出
print(color[0])

#修改
color[0] = 'white'
print(color)

#在末尾新增
color.append('black')
print(color)

#插入元素
color.insert(0,'yellow')
print(color)

#使用del刪除元素
del color[0]
print(color)

#使用pop刪除元素
#刪除棧頂
pop_color = color.pop()
print(pop_color)
print(color)

#刪除指定索引
pop_color = color.pop(0)
print(pop_color)
print(color)

#若不使用刪除值,使用del,否則使用pop

#刪除指定值
color.remove('blue')
print(color)

2.高階操作

#排序
color=['red','green','blue','purple']
print(color)
//從小到大
color.sort()
print(color)
//從大到小
color.sort(reverse=True)
print(color)

#臨時排序,不改變列表的值
color=['red','green','blue','purple']
print(sorted(color))
print(sorted(color,reverse=True))
print(color)

#列表翻轉
color.reverse();
print(color)

#列表長度
print(len(color))

3.訪問連結串列

#迴圈訪問
color=['red','green','blue','purple']
for col in color:
	print(col)

#建立數字列表
for value in range(1,10):
	print(value)

#數字列表統計
even_number = list(range(2,11,2))
print(even_number)
print(max(even_number))
print(min(even_number))
print(sum(even_number))

#切片
color=['red','green','blue','purple']
print(color[1:3])
print(color[:4])
print(color[1:])
print(color[:-1])

#複製列表
#僅生成一個新的變數名
color1 = color
#生成一個新的列表
color2 = color[:]