Python 數據結構之列表(list)
Python中的列表和元組相似,但可以對其中的元素進行修改,類似Java中的ArrayList
li = [1, 2, [apple, banana, orange]] # create a list called li
print(li[-1][-2])
li.insert(0, "Hello") # insert a string element "Hello" into li at the index 0
print(li)
li.append("good") # append string "good" to li
print(li)
li.append(["Google", "Baidu"]) # append a list to li
print(li)
li.remove([apple, banana, orange]) # remove the element 1 from li
print(li)
li.reverse() # reverse the sequence of elements in li
print(li)
li = li * 2 + [1, 2, 3] #
print(li)
li = [1, 45, 2, 16, 4, 4] # sort the element in li
li.sort()
print(li)
print(li.pop()) # remove the last element from li and print it
print(li.index(2, 0, 6))
運行結果:
[Hello, 1, 2, [apple, banana, orange]]
[Hello, 1, 2, [apple, banana, orange], good]
[Hello, 1, 2, [apple, banana, orange], good, [Google, Baidu]]
[Hello, 1, 2, good, [Google, Baidu]]
[[Google, Baidu], good, 2, 1, Hello]
[[Google, Baidu], good, 2, 1, Hello, [Google, Baidu], good, 2, 1, Hello, 1, 2, 3]
[1, 2, 4, 4, 16, 45]
45
1
根據列表的特性,可以用它來實現堆棧和隊列。如下:
- 堆棧的實現
# implement a stack
li = [1, 2, 3]
li.append(4) # push a new element onto a stack
print(li)
print("element poped: ", li.pop()) # remove an element from the stack
print(li)
運行結果:
[1, 2, 3, 4]
element poped: 4
[1, 2, 3]
2. 隊列的實現
# implement a queue
li = [1, 2, 3] # create a list
li.append(4) # add a new element to the list
print(li)
print("element poped:", li.pop(0)) # use index to specify the element that you want to remove from the list
print(li)
運行結果:
[1, 2, 3, 4]
element poped: 1
[2, 3, 4]
推薦閱讀: