Published 5月 29, 2018 by with 0 comment

快快樂樂學Python - 05

Python Lab

今天學list & tuple
1. list: []是一種集合, 可任意加減其中的元素
>>> year = ['2015', '2016', '2017', '2018']
>>> year
['2015', '2016', '2017', '2018']

2. 可用len()查list的元素有幾個
>>> len (year)
4

3. list中的元素, 按順序是從0開始, 最後一個為-1
>>> year [1]
'2016'
>>>
>>> year [-1]
'2018'

4. append: 加入元素到最後一個位址
>>> year.append ('2019')
>>> year
['2015', '2016', '2017', '2018', '2019']

5. insert: 加入元素到指定位址
>>> year.insert (2, '2017-Python')
>>> year
['2015', '2016', '2017-Python', '2017', '2018', '2019']

6. pop (): 刪除指定位址的元素. 不加數字是刪最後一個元.
>>> year
['2015', '2016', '2017-Python', '2017', '2018', '2019']
>>> year.pop (3)
'2017'
>>> year
['2015', '2016', '2017-Python', '2018', '2019']

7. 若直接[]寫索引位址, 就是把原本的元素做替換.
>>> year
['2015', '2016', '2017-Python', '2018', '2019']
>>> year [1] = '2016-Cisco'
>>> year
['2015', '2016-Cisco', '2017-Python', '2018', '2019']

8. list 內也可有其他的list
>>> year
['2015', '2016-Cisco', '2017-Python', '2018', '2019']
>>>
>>> yearQ
['2017', ['Q1', 'Q2', 'Q3', 'Q4'], '2018']
>>>
>>> len (yearQ)
3
>>>
>>> YearsQ = [year, yearQ, '2019']
>>> YearsQ
[['2015', '2016-Cisco', '2017-Python', '2018', '2019'], ['2017', ['Q1', 'Q2', 'Q3', 'Q4'], '2018'], '2019']
>>>
>>> len (YearsQ)
3
>>>
>>> YearsQ [1][1][1]
'Q2'
>>>

9. tuple: ()是一種集合, 不可加減其中的元素
>>> room = ('2801', '2802', '2803', '2804-Peter')
>>> room
('2801', '2802', '2803', '2804-Peter')
>>>

10. tuple()內加上一個list[]
>>> newroom = ('2801', '2802', ['A', 'B'], '2803')
>>> newroom
('2801', '2802', ['A', 'B'], '2803')
>>>
>>> newroom [2][0]
'A'
>>>
>>> newroom [2][1]
'B'
>>>

Example
# -*- coding: utf-8 -*-
#20170508
#05_01.py
#yesr為list, 內有2017,2018,2019三元素, 並印出來.
year = ['2016', '2017', '2018']
print (year)
#2017內再插入Q1, Q2, Q3, Q4, 並印出來
year.insert (1, 'Q1, Q2, Q3, Q4')
print (year)
#Room為tuple, 內有2803, 2804, 2805三元素, 2804內有list A 和 B兩元素, 並印出來.
Room = ('2803', '2804', ['A', 'B'], '2805')
print (Room)
#將 A 和 B 替換為 C 和 D, 並印出來
Room [2][0] = 'C'
Room [2][1] = 'D'
print (Room)


最初發表 / 最後更新: 2017.05.08 / 2018.05.29

0 comments:

張貼留言