Python


Posted by a113062130630210 on 2022-06-22

List Comprehension

想要建一個儲存1~10各個數字的平方的list

my_list = []
for i in range(1, 11):
    my_list.append(i * i)

利用list comprehension,可以寫成
my_list = [x * x for x in range(1, 11)]
語法是
[expression for item in iterable (if condition)]
例子:

list1 = [3, 0, -4, 5, -2, 1]
list2 = [x for x in list1 if x > 0]
# list2 = [3, 5, 1]
list3 = [[x, y] for x in range(2) for y in range(3)]
# [[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2]]
list4 = [[1, 2, 3], [4, 5, 2], [3, 2, 6]]
list5 = [x for l in list4 for x in l]
# [1, 2, 3, 4, 5, 2, 3, 2, 6]

Slicing

a[start:stop:step]
從start走到stop(不包含stop),每隔step取出一個元素
如果不指定的話,start = 0, stop = len(a), step = 1

a = ['0', '1', '2', '3', '4', '5', '6', '7']
print(a[1:6:2])
print(a[5:])
print(a[::-1]) #跟a.reverse()一樣意思
['1', '3', '5']
['5', '6', '7']
['7', '6', '5', '4', '3', '2', '1', '0']

Subscription

如果index是負數,那它的意思就變成len(a)+index
注意,0, -0都不是負數

a = ['0', '1', '2', '3', '4', '5', '6', '7']
print(a[-3])
print(a[-4:])
print(a[:-0]) # -0不是負數
5
['4', '5', '6', '7']
[]









Related Posts

Day 6 - While Loop & Karel

Day 6 - While Loop & Karel

「文章網址 slug 設定」是什麼?

「文章網址 slug 設定」是什麼?

[Release Notes] 20200924_v1 - Fix blog post serie checkbox bug & add publish type modal

[Release Notes] 20200924_v1 - Fix blog post serie checkbox bug & add publish type modal


Comments