追蹤者

2019年6月27日 星期四

用 Python 做商管程式設計(一) Week 5a

05-a01 字串切割成清單
---
   gradeStr = input() #1 2 3 4 5
   grade = gradeStr.split() #用空白切開,若要用comma切開則: split(',')
   print(grade) # grade 是一個list
---
List 
是一個 ordered container
字串內元素(item)可用index 操作
如上例:print(grade[0]) #1 , print(grade[2]*2) #33

len() 可得 listlist長度
print(len(grade)) #5

List 宣告
aList = [0] * 3 # [0,0,0]

append() 可新增Items 到 List
ex:
    gradeStr = input() #1 2 3 4 5
    grade = gradeStr.split()
    grade.append(-1)
    print(grade) # ['1','2','3','4','5',-1]
    grade.append([9,7,5])
    print(grade) # ['1','2','3','4','5',-1,[9,7,5]] , list裡面可以加list
    print(grade[6][1]) #7 , grade[6]為list ,可存取該list的元素

List 內  string  string  轉 int
ex:
    gradeStr = input()
    gradeList = gradeStr.split()
    print(gradeList)
    grades = []

    for g in gradeList: 
    grades.append(int(g))

    print(grades) #[1,2,3,4,5]
    #for 迴圈那邊可以替換成
    #for i in range(len(gradeList)):
    #    grades[i] = int(graedList[i])

range 複習
>>>range(10) # 从 0 开始到 10 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> range(1, 11) # 从 1 开始到 11 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

05-a03 List 相關函數

lst = [3,1,4,1,5,9]
lst.append(2)
print(lst)# [3, 1, 4, 1, 5, 9, 2], 新增2

lst.sort()

print(lst)# [1, 1, 2, 3, 4, 5, 9],list內數值排序

lst.reverse()

print(lst) # [9, 5, 4, 3, 2, 1, 1],list 內 item 翻轉

print(lst.index(4)) # 2 


lst.insert(4,"Hi")

print(lst)#[9, 5, 4, 3, 'Hi', 2, 1, 1] ,在第4個index位插入""

print(lst.count(1))# 2 , 數字1出現幾次


lst.remove(1)

print(lst)# [9, 5, 4, 3, 'Hi', 2, 1] ,移除掉第一個出現的 1

print(lst.pop(3))# 3 ,把 3 拿出來



print(lst)# [9, 5, 4, 'Hi', 2, 1]

List Copying
ex:
aList = [1,2,3]
bList = aList
bList[0] = 5
print(bList) #[5,2,3]

Why?
Python 中 list variable 是一個 reference
Copying a list is just copying the reference ,not those values

順序:
1.aList 參照 [1,2,3]
2.aList 的內容 copy 到 bList,有兩個list分別寫著[1,2,3]這塊地的地址
3.aList 和 bList並非兩個lists, 而是一個list的兩個名字
4.若要做到兩個lists 使用 append 把item 依序 複製進去

1 則留言:

  1. Tiamin' Xion's Xion's Xion's Xion's Xion's Xion's Xion's Xion
    Our Xion Xion's edc titanium Xion's Xion's Xion's Xion's Xion's Xion's Xion's Xion's columbia titanium jacket Xion's Xion's titanium nitride coating Xion's titanium jewelry piercing Xion's Xion's Xion's Xion's Xion's Xion's Xion's Xion's Xion's stilletto titanium hammer Xion's

    回覆刪除