索引
python比較神奇,可以從正面數或反著數,每一個位置都有自己的下標
切片
假設現在有一陣列
a = [1, 2, 3, 4, 5]
print(a[0:4:2])
# [1, 3, 5]
# a是陣列的名稱
# []裡面的第一個數字是起點(start)
# 第二個是終點(end)
# 第三個是間隔(step)
a = [1, 2]
b = [3, 4]
print(a + b)
# [1, 2, 3, 4]
a = [1, 3, 5]
print(5 in a)
# True
a = [1, 3, 5, 7, 9]
print(len(a), max(a), min(a))
# 5 9 1
# 直接創建
name = [element1, element2, ...]
# 創建空陣列
name = []
# 使用list()函數
nums = list(range(10))
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
name = [1, 2]
del name
name = [1, 2, 3]
print(name[2])
# 3
name = [1, 2, 3, 4]
# 使用for迴圈
for item in name:
print(item, end = '')
# 使用for迴圈和enumerate()函數
for index, item in enumerate(name):
print(index, item)
# append()是加在屁股後面的
name = [1, 2, 3]
name.append(4)
print(name)
# [1, 2, 3, 4]
# 也可以使用insert(),但效率不高,不推薦使用
# 使用extend()將2個陣列加在一起
name2 = [5, 6]
print(name.extend(name2))
[1, 2, 3, 4, 5, 6]
name = [0, 1, 3, 3]
name[2] = 2
print(name)
#[0, 1, 2, 3]
name = [0, 1, 2, 3]
# 根據index值
del name[3]
# [0, 1, 2]
# 根據元素值
name.remove(2)
# [0, 1]
nums = [0, 1, 1, 2, 3, 3]
print(nums.count(1))
# 2
# index(object)
nums = [0, 1, 1, 2, 3]
answer = nums.index(1)
print(answer)
# 1
# sum(listname[, start])
nums = [0, 1, 2, 3]
answer = sum(nums)
print(answer)
# 6
# namelist.sort(key = None, reverse = True)
# key是比較的鍵(值)
# reverse則可指定是升序或降序
nums = [0, 5, 1, 2, 3, 4]
nums = nums.sort()
print(nums)
# [0, 1, 2, 3, 4, 5]
nums = nums.sort(reverse = False)
print(nums)
# [5, 4, 3, 2, 1, 0]
# 簡單明瞭的意思是把sort()反過來看就好
nums = [0, 2, 5, 6, 1]
nums = sorted(nums)
print(nums)
# [0, 1, 2, 5, 6]
# list = [表達式 for 循環變量 in range()]
nums = [i for i i in range(10)]
print(nums)
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# list = [表達式 for 循環變量 in 原陣列]
nums = [0, 1, 2, 3]
new_nums = [x*0.5 for x in nums]
print(new_nums)
# [0.0, 0.5, 1.0, 1.5]
nums = [0, 1, 2, 3, 5, 9]
new_nums = [x for x in nums if x % 3 == 0]
print(new_nums)
# [0, 3, 9]
# [[00, 01, 02, 03],
# [10, 11, 12, 13],......]
test = []
for i in range(4):
test.append([])
for j in range(5):
test[i].append(j)
print(test)
# [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]
nums = [[i for i in range(5)] for j in range(4)]
print(nums)
# [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]
# 是(),不是[],[]是陣列非元組
nums = (1, 2, 3)
# 其實未必要用(),用 , 隔開就可以了
nums = '0', '1', '2'
print(nums)
# ('0', '1', '2')
empty = ()
# tuple(data)
nums = tuple(range(0, 5, 2))
print(nums)
# (0, 2, 4)
# 直接刪除即可
nums = (0, 1, 2)
del nums
nums = (0, 1, 2)
print(nums[0])
# 0
print(nums[0:2])
# (0, 1)
nums = (0, 1, 2)
nums = (1, 2)
print(nums)
# (1, 2)
nums = (0, 1, 2)
add_nums = (3, 4)
print(nums + add_nums)
# (0, 1, 2, 3, 4)
import random
nums = (random.randint(10, 100) for i in range(10))
print(nums)
# <generator object <genexpr> at 0x0000016C21DD8190>
這邊還需要一個tuple,因為元組推導式生成的結果不是一個元組,所以還需要轉換
加上
nums = tuple(nums)
print(nums)
# (24, 23, 59, 81, 35, 46, 18, 60, 89, 87)
nums = (i for i in range(3))
print(nums.__next__())
# 0
print(nums.__next__())
# 1